how to initialize arraylist of arraylist - java

Following line will initialize arraylist with 9 elements with value true.
public ArrayList<Boolean> timeTable = new ArrayList<Boolean>(Collections.nCopies(9, true));
But how can i initialize arraylist of arraylist?
public ArrayList<ArrayList<Boolean>> timeTable = new ArrayList<ArrayList<Boolean>>(Collections.nCopies(9, true));
It should mean that outer arraylist has 9 inner arraylist and each inner arraylist has 9 elements with true value.
Similar to How can I initialize an ArrayList with all zeroes in Java?
But not exactly same...
Scenario is that i need to maintain a monthly list of daily timetables. Now daily timetable will have only 9 entries, so immutable is fine. But monthly list needs to be appended each month. So it can't be an arraylist.

Given this line form java docs: "Returns an immutable list consisting of n copies of the specified object"
public ArrayList<Boolean> timeTable = new ArrayList<Boolean>(Collections.nCopies(9, true));
public ArrayList<ArrayList<Boolean>> timeTableLists = new ArrayList<ArrayList<Boolean>>(Collections.nCopies(9, timeTable));

Firstly, it is recommended to use interface types wherever possible. That would make your
ArrayList<ArrayList<Boolean>> -> List<List<Boolean>>.
Then, the initialization statement would become
public List<List<Boolean>> timeTable = Collections.nCopies(9, (Collections.nCopies(9, true)));

Related

how to pass data from one array list to another array list [duplicate]

This question already has answers here:
Java ArrayList copy
(10 answers)
Closed 6 years ago.
I have an array list of:
ArrayList<ItemsBean> itemsList1 = new ArrayList<ItemsBean>();
I called the data from data base and added to this Arraylist
while (items.next()) {
ItemsBean bean = new ItemsBean();
bean.setInvNo(items.getString("Invoice_Number"));
bean.setItemnNameDisplay(items.getString("Prodname"));
bean.setParentobjectid(items.getString("ParentObjectID"));
bean.setQuantityDisplay(items.getInt("Quantity"));
bean.setProdnum(items.getInt("ProdNum"));
itemsList1.add(bean);
}
Now I have new array list:
ArrayList<ItemsBean> newListitems2 = new ArrayList<ItemsBean>();
now I want to pass same data to this new array list in same activity
You can either use addAll() or try like this arraylist2 = arraylist1 .
addAll() is like below
arraylist2.addAll(arraylist1);
Hope this is helpful :)
ArrayList newListitems2 = new ArrayList(itemsList1);
ArrayList has constructor, receiving Iterable<> as argument, so you cancreate new list with values from another list. Notice, values will remain the same, ArrayList only contains references to actual objects.

Collections.sort() affects all ArrayLists. How do I sort only one list and not the others?

I have three ArrayLists:
One is used for storing user input in the order they were entered, located in the main class.
Second one is exactly the same as the first one, but it is passed into a method called remTrip to be copied and will return the result.
Third one is list1 in the code below, which is the one being processed.
public static ArrayList<String> remTrip( ArrayList<String> a){
//code here
ArrayList<String> list1 = a;
Collections.sort(list1);
//code to remove triplicates from the list and returns the result
}
I wanted to keep the first ArrayList<String> in the same order it was (i.e. {"dog", "cat" , "tiger", "cat", "cat"} ), but apparently the Collections.sort() sorts all of the ArrayLists.
How do I sort only one of the list and not the others?
The problem is not how Collections.sort() works. The problem is that instead of creating a copy of your list, you set the new list equal to your list. This means that they both point to the same object, sorting one will sort the other because they are the same thing. To solve this set list1 to a copy of a instead of setting them equal.
You should be able to do
ArrayList<String> list1 = new ArrayList<String>(a);
Three arralists you're talking about are not 3 different arraylists. They're just three different references to the same arraylist.
What you're doing essentially is -
List list01 = new ArrayList();
List list02 = list01;
List list03 = list01;
What you want is -
List list01 = new ArrayList();
List list02 = new ArrayList(list01);
List list03 = new ArrayList(list01);
But you should remember, this way will give you a copy of your List, not all it's elements. So, if you change one of the elements in your copied List, it will be changed in your original List too.
How to solve it - Hint copy constructor.

ArrayList. Strange things

I have the code:
private class Record {
byte year;
float val;
}
Record record=new Record();
List<Record> recList = new ArrayList<Record>();
...
//now I add first element to array list
record.year=12;
record.val=55;
recList.add(record);
//now I add second element to array list
record.year=13;
record.val=77;
recList.add(record);
As you see I add different elements.
But as a result all elements in array list are the same.
So adding 2-nd, 3-d... element changes all previous elements
to the values of last "record".
What's wrong? Thanks?
An ArrayList keeps a list of references to objects. You're always modifying the same original object which means the reference is the same, but its values differ.
You can fix it by explicitly assigning a new instance to the record variable:
record.year=12;
record.val=55;
recList.add(record);
record = new Record();
record.year=13;
record.val=77;
recList.add(record);
You need to instantiate new objects so they are physically different objects. Right now, you only have one object that is in the ArrayList multiple times.
Record record = new Record();
Also, you should add hashCode() and equals() to Record since you are working with collections.
As you see I add different elements
No, you just edited old Record object and added it again. Each time before you add Record object you need to crate new one.

Getting only last element of arraylist and losing old elements

I have a problem about Arraylists. I created an arraylist of user defined object. In my drawing program, I created a class which takes only this arraylist. In another class I create this object, and I create another arraylist which takes these objects. You can understand better if you can look up my code. The problem is I have to remove all elements of the object's arraylist after adding to the last arraylist. But I always lose elements after removing. I used clone() method then I keep always last elements. I know its coplicated here, sorry about my english, you can understand clearly what I mean if you can check my code.
public class Lines {
public int id;
public Point point1;
public Point point2;
public int[] denklem;
}
public class Devline {
ArrayList<Lines> segmentim = new ArrayList<Lines>();
}
...
Devline devarray = new Devline();
Devline devarray3 = new Devline();
ArrayList<Devline> devarray2 = new ArrayList<Devline>();
if(SwingUtilities.isRightMouseButton(e) == true){
devarray3.segmentim = (ArrayList<Lines>) devarray.segmentim.clone();
devarray2.add(devarray3);
devarray = new Devline();
begin = true;
}
Here how I add an element to devarray.
devarray.segmentim.add(l1);
I need to add all elements to my devarray2 list. Each time I click rightbutton it will add devarray elements into devarray2, so I can make many different devarray elements inside devarray2. Thank you.
devarray3.segmentim = (ArrayList<Lines>) devarray.segmentim.clone();
devarray2.add(devarray3);
You are repeatedly adding the same Devline object to the ArrayList. Its segmentim is getting changed bu it is affecting all elements in the ArrayList.
You need to add a new Devline to the devaray2 ArrayList in each iteration. Since you are creating new devarray you can use that one itself:
devarray2.add(devarray);
devarray = new Devline();
begin = true;
Also you should change the names -- devarray is not an array, it should be devLine and the class Lines should be called Line
Could you try
devarray3.segmentim = new ArrayList<Lines>(devarray.segmentim);
to copy the devarray2 arraylist ?

OOP: Difference between ArrayList al = new ArrayList() and List al = new ArrayList()? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
List versus ArrayList
Difference between
ArrayList al = new ArrayList()
and
List al = new ArrayList() ?
None, from a creation perspective. Both create an instance of ArrayList.
The difference is that, in you second example, al allows access to all methods implemented on the List interface while, in the first example, al allows access to all (accessible) methods and fields of the ArrayList class.
A practical rule of thumb: use the second pattern. If you need some extra goodies from the ArrayList implementation, then you can always cast:
List list = new ArrayList();
// do some adds/removes/... on the list
((ArrayList) list).trimToSize();
Its called programming to interface. Suppose, you need to return this list from your method. So the calling code can have that into a List variable.
public ArrayList getList() {
ArrayList list = new ArrayList();
// do something with the list here
return list;
}
And this,
public List getList() {
List list = new ArrayList();
// do something with the list here
return list;
}
Now for the latter method calling code can have the returned list in List type variable. And you can easily decide later, for some reason, something like this,
public List getList() {
List list = new LinkedList();
// do something with the list here
return list;
}
No change in calling code, whereas with the former you need to change the return type, that would eventually screw up the calling code as well.
Paraphrasing my answer to this very similar question about Map vs. HashMap:
There is no difference between the objects. There is a difference in the interface you have to the object. In the first case, the interface is ArrayList, whereas in the second it's List. The underlying object, though, is the same.
The advantage to using List is that you can change the underlying object to be a different kind of list without breaking your contract with any code that's using it. If you declare it as ArrayList, you have to change your contract if you want to change the underlying implementation.

Categories

Resources