I have an home work,I used an array and element of array is linked list because the element in a row is not fixed need delete or add some time depend on problem condition , I was tried these codes below, but I have a problem when adding new element to a fixed row for example p[0] the value will be added for all, how I can solve this problem please help.
public class schedule
{
public class link
{
public LinkedList <Integer>list = new LinkedList<Integer>() ;
public link(LinkedList<Integer> value)
{
list = value;
}
public link(int value)
{
list.add(Integer.valueOf(value)) ;
}
}
private link p[] = new link[10];
public schedule()
{
LinkedList<Integer> l = new LinkedList<Integer>();
l.add(Integer.valueOf(2));
l.add(Integer.valueOf(0));
l.add(Integer.valueOf(3));
for(int j=0;j<p.length;j++)
p[j] = new link(l);
p[0].list.add(9); // here I have problem
for(int j=0;j<p.length;j++)
{
System.out.print("p["+j+"]:");
for(int i=0;i<p[j].list.size();i++)
System.out.print(p[j].list.get(i).intValue());
System.out.println();
}
}
public static void main(String []arg)
{
new schedule();
}
the output is like this : the value 9 added to all but I want to be added just for first element
p[0]:2039
p[1]:2039
p[2]:2039
p[3]:2039
p[4]:2039
p[5]:2039
p[6]:2039
p[7]:2039
p[8]:2039
p[9]:2039
The problem is that you're initializing every link instance with the same LinkedList<Integer>:
LinkedList<Integer> l = new LinkedList<Integer>();
l.add(Integer.valueOf(2));
l.add(Integer.valueOf(0));
l.add(Integer.valueOf(3));
for(int j=0;j<p.length;j++)
//it will be the same LinkedList<Integer> l per all the instances in the array
p[j] = new link(l);
Take note that when you do this, every link instance will have the list attribute referencing the same LinkedList<Integer> l variable. So, if you modify it in one place, everyone will be updated (because it's the same reference).
There are many ways to solve this:
Create a new LinkedList on every iteration of your for loop.
Create the new link instance using another constructor.
Fill your link[] p array one by one...
Related
Not sure how I can achieve this.
I have a object list, where it consists of multiple data example
ABC1231211
ABC1231111
ABC4562222
ABC4562456
Now I trying to seperate the list according to their code, which is 123 and 456, and add header and tailer to them. So my expected result would be
Head
ABC1231211
ABC1231111
Tail
Head2
ABC4562222
ABC4562456
Tail2
But the result I get is
Head
ABC1231211
Tail
Head
ABC1231111
Tail
Head2
ABC4562222
Tail2
Head2
ABC4562456
Tail2
Code
#Override
public List process(List<Detail> l) throws Exception {
for (Detail d : l) {
if (d.Code().equals("123")) {
list = generateS(d);
}
if (d.Code().equals("456")) {
list = generateR(d);
}
}
return list;
}
public List<String> generateS(Detail d) throws Exception {
try {
list.add(new HDR("Head").getHeader());
DetailL x = new DetailL();
x.setType(d.getType());
....
list.add(x.getDetail());
list.add(new TLR("Tail").getTailer());
} catch (Exception ex) {
throw new BatchException(DetailProcessor.class, ex);
}
return list;
}
Any help would be much appreciated
If you're using Java 8, you can use streams:
public void process(List<Detail> details) throws Exception {
Map<String, List<Detail>> byCode =
details.stream().collect(Collectors.groupingBy(Detail::getCode));
byCode.entrySet().stream().forEach(entry -> {
System.out.println(headerFromType(entry.getKey()));
entry.getValue().foreach(System.out::println);
System.out.println(tailFromType(entry.getKey()));
}
with headerFromType and tailFromType returning "Head"/"Head2" or "Tail"/"Tail2", depending on the given type.
You are generating a new head and tail for each element instead of adding to the already-generated list.
For each Detail, you should first check if the list exists, and if it doesn't, then call generateS or generateR as appropriate. If the list exists, you want to call e.g. sList.add(sList.size()-1, d.getDetail()). You'll of course want to replace the call d.getDetail() with the value that's supposed to go into the list or a method call that returns that value.
Then you probably want to use list.addAll(sList) to add the generated lists' contents to list.
Another solution is to generate the combined list on demand, and store the two lists separately. In that case, you would check if the corresponding list is null in the beginning of generateS or generateR, and initialize it if it is.
You create a new header and a new tail every time you call generateS or generateR but you should just create a new header once if you find a new code ( for example 123).
Solution: You collect your details into a list before you call generateS or generateR and put all the details from collected list into your DetailL.
Here is another implemetation that takes another approach:
private void go() {
List<String> list = new ArrayList<>();
list.add("ABC1231211");
list.add("ABC1231111");
list.add("ABC4562222");
list.add("ABC4562456");
String lastTag = null;
int startPos = 0;
for (int i = 0; i < list.size(); i++) {
String tag = list.get(i).substring(3, 6);
if (!tag.equals(lastTag) && lastTag != null) {
print(list.subList(startPos, i));
startPos = i;
}
lastTag = tag;
}
print(list.subList(startPos, list.size()));
}
private void print(List<String> list) {
System.out.println("Head");
for (String item : list) {
System.out.println(item);
}
System.out.println("Tail");
}
Simply "If you come accross an element with a different tag, print the previous sublist". (And print whatever is left at the end since that sublist's printout is not triggered by a new tag.)
I am trying to find out if there is a possibility of returning the updated ArrayList after removing the specified element at the index in a single line so that I can pass it on to the recursive function.
Below is a snippet of my code which tries to generate all valid parenthesis combinations given n pairs of "()" brackets.
My concern is in the recursive function call "findAllCombinations" where after some validations I want to remove one character at each recursive call from the arrayList courceSet. However sourceSet.remove(index) returns a character. Instead I want to pass the updated list after removing the character in one line. Is it possible ?
Note : The line below is syntactically wrong and just used for better illustration.
findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket); .
I did go through the official documentation but did not find any help.
Any help is appreciated, and thanks for your time.
public class GenerateParenthesis {
char singleBracket;
List<String> answerSet = new ArrayList<String>();
char[] repoSet = {'(',')'};
public List<String> generateParenthesis(int n) {
String soFar = "(";
List<Character> sourceSet = new ArrayList<Character>();
for(int i = 0;i<n;i++){
sourceSet.add('(');
sourceSet.add(')');
}
findAllCombinations(sourceSet,soFar,'(');
return answerSet;
}
public void findAllCombinations(List<Character> sourceSet,String soFar,Character toRemove){
if(sourceSet.isEmpty()){
answerSet.add(soFar); // append to a answer set list containing all combinations
return;
}
for(int i = 0;i<2;i++){
singleBracket = repoSet[i];
int index = sourceSet.indexOf(singleBracket);
if(index!=-1) {
findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket);
}
}
}
public static void main(String args[]){
GenerateParenthesis gp = new GenerateParenthesis();
List<String> ans = new ArrayList<String>();
ans = gp.generateParenthesis(3);
}
}
ArrayList (likely to most List implementations) is a mutable data structure: calling remove you modify the list rather than returning a new list without the removed element.
If you want the latter behavior, the quick and easy way is to do a copy of the list.
// (inside the if...)
// pass the original list to the constructor to make a copy
List<Character> sourceSetCopy = new ArrayList<>(sourceSet);
// modify the copy
sourceSetCopy.remove(index);
// use the modified copy
findAllCombinations(sourceSetCopy, soFar + singleBracket, singleBracket);
I was wondering if you could help me with this problem, I'm stuck for a day in trying to solve this one. So basically what I want to do is have a list that will contain an array of an array.
I have this initialization
List<double[][]> points = new ArrayList<double[][]>();
I add the elements this way:
points.add(existing.Foods);
My beeColony class contains the data that I want to add:
public class beeColony{
double Foods[][]=new double[FoodNumber][D];
....
}
And here's how I declare an instance of it:
public beeColony existing=new beeColony();
Here's a snippet of the code:
for(run=0;run<existing.runtime;run++)
{
for (iter=0;iter<existing.maxCycle;iter++)
points.add(existing.Foods);
}
What happens is that when I output all the items the list, it only contains the last added items.
for example:
Foods = {(0,0), (1,1), (2,2), (3,3)}
points.add(Foods);
Foods = {(4,4), (5,5), (6,6), (7,7)}
points.add(Foods);
The way that I understand it is that
points.get(0)[0] should countain 0,0 and so on and points.get(1)[0] should contain 4,4 and so on. But what happens is points.get(0) also has the same values as points.get(1)
Collections like ArrayList<X> contain references to X objects, like one end of a string the other end of which is "tied" to the object itself, i.e., where the data resides.
This is also true for arrays like double[][].
What you do is to copy and store the reference end repeatedly, but at the other end there is one and the same double[][]. You can change the contents of that array, but all stored string ends lead to the same array object.
You must create new copies of that array to hold different array values. If you create another BeeColony, it will have another foods array. Otherwise, use new double[m][n] and copy the values. This is how:
double[][] d = { {1,2}, {3,4}, {5,6} };
// create the vector of (still missing) rows:
double[][] copy = new double[d.length][];
for( int row = 0; row < d.length; ++row ){
// create another row of appropriate length:
copy[row] = new double[d[row].length];
// copy the element values
System.arraycopy( d[row], 0, copy[row], 0, d[row].length );
}
PS: You should stick to Java conventions. Classe names are written in camel case starting with an upper case letter; variables and methods should start with a lower case letter. Loops should declare the loop counter inside the for: for( int run = 0;... ). Avoid public for class fields; code getters and setters to access private class fields.
You could use combination of array and iterator to get the work done,
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class listerr {
static int getrandom(){
Random r = new Random();
int next = r.nextInt(100);
return next;
}
static double[][] getarr(){
double[][] arr = {{getrandom(),getrandom()}, {getrandom(),getrandom()},
{getrandom(),getrandom()}, {getrandom(),getrandom()}};
return arr;
}
public static void main(String[] args) {
List<double[][]> points = new ArrayList<double[][]>();
for(int run=0;run<3;run++)
{
double[][] arr = getarr();
points.add(arr);
}
Iterator itr = points.iterator();
while(itr.hasNext()){
double[][] dbl = (double[][]) itr.next();
for (int i=0;i<4;i++)
{ for (int j=0;j<2;j++){
System.out.println(dbl[i][j]);
}
}
}
}
}
I am trying to write a method that takes an ArrayList of Strings as a parameter and that places a string of four asterisks in front of every string of length 4.
However, in my code, I am getting an error in the way I constructed my method.
Here is my mark length class
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
And the following is my main class:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
ish.marklength4(words);
}
}
Essentially in this case, it should run so it adds an arraylist with a string of "****" placed before every previous element of the array list because the lengths of the strings are all 4.
BTW
This consists of adding another element
I am not sure where I went wrong. Possibly in my for loop?
I got the following error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Marklength.marklength4(Marklength.java:7)
at MarklengthTestDrive.main(MarklengthTestDrive.java:18)
Thank you very much. Help is appreciated.
Let's think about this piece of code, and pretend like you don't get that exception:
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
Ok, so what happens if your list just contains item.
You hit the line if(n.length() ==4){, which is true because you are looking at item, so you go execute its block.
Next you hit the line themarklength.add("****");. Your list now has the element **** at the end of it.
The loop continues, and you get the next item in the list, which happens to be the one you just added, ****.
The next line you hit is if(n.length() ==4){. This is true, so you execute its block.
You go to the line themarklength.add("****");, and add **** to the end of the list.
Do we see a bad pattern here? Yes, yes we do.
The Java runtime environment also knows that this is bad, which is why it prevents something called Concurrent Modification. In your case, this means you cannot modify a list while you are iterating over it, which is what that for loop does.
My best guess as to what you are trying to do is something like this:
import java.util.ArrayList;
public class Marklength {
ArrayList<String> marklength4(ArrayList <String> themarklength){
ArrayList<String> markedStrings = new ArrayList<String>(themarklength.size());
for(String n : themarklength){
if(n.length() ==4){
markedStrings.add("****");
}
markedStrings.add(n);
}
System.out.println(themarklength);
return markedStrings;
}
}
And then:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
words = ish.marklength4(words);
}
}
This...
if(n.length() ==4){
themarklength.add("****");
}
Is simply trying to add "****" to the end of the list. This fails because the Iterator used by the for-each loop won't allow changes to occur to the underlying List while it's been iterated.
You could create a copy of the List first...
List<String> values = new ArrayList<String>(themarklength);
Or convert it to an array of String
String[] values = themarklength.toArray(new String[themarklength.size()]);
And uses these as you iteration points...
for (String value : values) {
Next, you need to be able to insert a new element into the ArrayList at a specific point. To do this, you will need to know the original index of the value you are working with...
if (value.length() == 4) {
int index = themarklength.indexOf(value);
And then add a new value at the required location...
themarklength.add(index, "****");
This will add the "****" at the index point, pushing all the other entries down
Updated
As has, correctly, been pointed out to me, the use of themarklength.indexOf(value) won't take into account the use case where the themarklength list contains two elements of the same value, which would return the wrong index.
I also wasn't focusing on performance as a major requirement for the providing a possible solution.
Updated...
As pointed out by JohnGarnder and AnthonyAccioly, you could use for-loop instead of a for-each which would allow you to dispense with the themarklength.indexOf(value)
This will remove the risk of duplicate values messing up the index location and improve the overall performance, as you don't need to create a second iterator...
// This assumes you're using the ArrayList as the copy...
for (int index = 0; index < themarklength.size(); index++) {
String value = themarklength.get(index);
if (value.length() == 4) {
themarklength.add(index, "****");
index++;
But which you use is up to you...
The problem is that in your method, you didn't modify each string in the arraylist, but only adds 4 stars to the list. So the correct way to do this is, you need to modify each element of the arraylist and replace the old string with the new one:
void marklength4(ArrayList<String> themarklength){
int index = 0;
for(String n : themarklength){
if(n.length() ==4){
n = "****" + n;
}
themarklength.set(index++, n);
}
System.out.println(themarklength);
}
If this is not what you want but you want to add a new string "**" before each element in the arraylist, then you can use listIterator method in the ArrayList to add new additional element before EACH string if the length is 4.
ListIterator<String> it = themarklength.listIterator();
while(it.hasNext()) {
String name = it.next();
if(name.length() == 4) {
it.previous();
it.add("****");
it.next();
}
}
The difference is: ListIterator allows you to modify the list when iterating through it and also allows you to go backward in the list.
I would use a ListIterator instead of a for each, listiterator.add likely do exactly what you want.
public void marklength4(List<String> themarklength){
final ListIterator<String> lit =
themarklength.listIterator(themarklength.size());
boolean shouldInsert = false;
while(lit.hasPrevious()) {
if (shouldInsert) {
lit.add("****");
lit.previous();
shouldInsert = false;
}
final String n = lit.previous();
shouldInsert = (n.length() == 4);
}
if (shouldInsert) {
lit.add("****");
}
}
Working example
Oh I remember this lovely error from the good old days. The problem is that your ArrayList isn't completely populated by the time the array element is to be accessed. Think of it, you create the object and then immediately start looping it. The object hence, has to populate itself with the values as the loop is going to be running.
The simple way to solve this is to pre-populate your ArrayList.
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>() {{
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
}};
}
}
Do tell me if that fixes it. You can also use a static initializer.
make temporary arraylist, modify this list and copy its content at the end to the original list
import java.util.ArrayList;
public class MarkLength {
void marklength4(ArrayList <String> themarklength){
ArrayList<String> temp = new ArrayList<String>();
for(String n : themarklength){
if(n.length() ==4){
temp.add(n);
temp.add("****");
}
}
themarklength.clear();
themarklength.addAll(temp);
System.out.println(themarklength);
}
}
I have a list like this
List contains set of dtime,uptime values.I want to get the list items i.e., dtime into one and
uptime into another variable.Likewise I want to get all the dtime and uptime pair values seperatly into
the variables using for loop in java.How can I achieve this.Is it possible list or vector?Please help me.
Pseudo code
List.get(0).get(0)-->gives 1st dtime
List.get(0).get(1)-->gives 1st uptime
List.get(1).get(0)-->gives 2nd dtime
List.get(1).get(1)-->gives 2nd uptime
And so on..
How to implement this with for loop I am not getting.I am new to java>please help me..
First Convert That ArrayList into Object[] array then get the value like given below code...driver_ModelsObj is an array convert that into drives object array then get the value from inside the array.
for(int indx=0;indx<driver_ModelsObj.size();indx++){
Object[] drivers=(Object[]) driver_ModelsObj.get(indx);
String Device_ID=drivers[0].toString();
}
If your list is as below
List list = [[1],[2],[3]];
We can retrieve the each value as below.
((List)list.get(0)).get(0); //This will retrieve value 1
((List)list.get(1)).get(0); //This will retrieve value 2
Sounds like you could use a domain object containing uptime and downtime.
For example,
public class Stats {
int dtime;
int uptime;
}
Then you can have a List<Stats> and access it like this:
mylist.get(0).dtime
mylist.get(0).uptime
mylist.get(1).dtime
mylist.get(1).uptime
Part of the (newer) Collcetions framework, List is almost always a better alternative than Vector
List.get(0).get(0)-->gives 1st dtime
List.get(0).get(1)-->gives 1st uptime
Well, what you're doing here, is getting the list at position 0, and getting item 1 from that list. In a for loop we can express this as:
for(int x = 0; x < List.size(); x++)
{
for(int y = 0; y < List.get(x).size(); y++)
{
if(y % 2 == 0)
{
// It's a dtime object.
}
else
{
// It's an uptime object.
}
}
}
Before this, you could declare some lists of your own:
List<DTime> listD = new ArrayList<ATimeObject>();
List<UpTime> listUp = new ArrayList<UpTime>();
Now when you're cycling through, all you need to do is add the relevant object:
if(y % 2 == 0)
{
listD.add(List.get(x).get(y));
}
else
{
listUp.add(List.get(x).get(y));
}
You should create a POJO like
public class TimeData {
double dtime;
Date uptime;
}
Then add each POJO to array list and then iterate it.
List<TimeData> oList = new ArrayList<TimeData>();
int nSize = oList.size();
for(int i=0;i<nSize;i++){
TimeData child = oList.get(i);
// get value using getters
}
You can try this ,Let say you have variables like
double dtime;
Timestamp tp;
And listofresults is coming from query results.
listofresults = results.getResultList();
If list is coming from query then put it in the loop this way in the condition of for loop
for(int i=0;i< listofresults.size() ;i=i+2)
{
dtime=(double) listofresults.get(i);
//cast because the value is of object type
tp=(TimeStamp) listofresults.get(i+1);
//cast because the value is of object type
//do something with these variables
}
I recommend creating a wrapper for it.
public class UpTimeDownTime {
MyTimeDataClass downtime;
MyTimeDataClass uptime;
public UpTimeDownTime(MyTimeDataClass downtime, MyTimeDataClass uptime){
this.downtime = downtime;
this.uptime = uptime;
}
public MyTimeDataClass getDowntime () {
return downtime;
}
public MyTimeDataClass getUptime () {
return uptime;
}
public static void main (String[] args) {
List<List<MyTimeDataClass>> List = ...;
List<UpTimeDownTime> uptimeDowntime = new ArrayList<UpTimeDownTime>();
for(List<MyTimeDataClass> timeList : List){
UpTimeDownTime u = new UpTimeDownTime(timeList.get(0), timeList.get(1));
uptimeDowntime.add(u);
}
}
}