What is the use of ArrayList<ArrayList<E>> - java

Can you give any reasonable example for a ArrayList<ArrayList<E>>, such as declaring, initializing, adding elements and iterating them. Is this one of the way to get 2-dimensional Array behavior in Java?

Yes, an ArrayList<ArrayList<E>> is similar to a two-dimensional array of E (E[][]). It has all the common differences between using a List and using arrays in Java (List is a higher-level API, supports resizing, adding elements at arbitrary positions, ...).
You don't treat it any different from a normal List, except that the elements it contains are actually other List objects:
Initialize it:
ArrayList<ArrayList<E>> listOfLists = new ArrayList<ArrayList<E>>();
Iterate over it:
for (ArrayList<E> innerList : listOfLists) {
doSomethingWithInnerList(innerList);
}
Add to it:
ArrayList<E> newInnerList = new ArrayList<E>();
// add stuff to newInnerList
listOfLists.add(newInnerList);

The only thing I want to add to Joachim Sauer's answer is that yes, an ArrayList<ArrayList<E>> can be similar to a two-dimensional array of E (E[][]) with one additional twist (in addition to all the usual differences between one-dimensional arrays and lists):
Using a list of lists, you can make the equivalent of a "jagged" array. Not all of the inner lists need to have the same size(), whereas in a two-dimensional array, all of the "rows" of E[][] by definition have identical lengths. It's "rectangular". A list of lists doesn't have to be rectangular; it can be jagged.

ArrayList is used to hold array of objects. On the other it can have duplicate values. when you need a fast insertion/deletion you can use it. it holds the values in the same order as it is entered into it. For example
List<String> ls= new ArrayList<String>();
ls.add("foo");
ls.add("bar");
for(String val:ls){
System.out.println("Value :" + val);
}

Related

After using Arrays.sort() how do I reverse array to its initial position?

I had to sort array to find its Median, but now I need to recover the initial value of array, put it as it was. Is that possible?
You can't do that. Sorting is irreversible. However, you could also add all elements of your original list to a new ArrayList and then sort that list.
List<String> original = ...;
List<String> copy = new ArrayList<>(original);
Collections.sort(copy);
I would not worry about the footprint of the copy. It is a shallow copy, that means that the elements themselves are not copied, but only a new list is created with references to the elements contained in the original list. And that operation is quite fast. I would only worry if the list was very, very big.
Using #McEmperors answer but with arrays
Object[] saved = Arrays.copyOf(old, old.length);
Array.sort(old);
There are several ways to achieve what you want:
copy the array before sorting
int[] unsorted = {2,3,1};
int[] sorted = unsorted.clone();
Arrays.sort(sorted);
//find mean in sorted then proceed with unsorted
create a custom sort function that retains a mapping between the positions.
find the mean without sorting

Connecting Array Index with Linked List

I am trying to implement Bucket Sort in Java without using Collections framework, on my own. I have a problem in implementing it.
I wanted to store a list of elements in a particular array index.
For Ex:
arr[0]={1,2,3,4}; //Here Array index 0 will be storing 4 values.
So I chose to have a linked list to store those values and then to map the array index with that linked list.
But I am not aware of how to map an Array index to a Linked List.
For Ex:
arr[0]->LinkedList1
arr[2]->LinkedList2
// ... and so on
Please suggest how to implement it.
In Java, arrays or Collections are simply a collection of objects of the same type. So, for your requirement, what you need is an array of lists.
List[] arrayOfLists = {};
This creates an array whose each member is a list (You can also create an array of LinkedList if you like).
Now, create a LinkedList and assign it to index 0 of the array.
LinkedList list1 = new LinkedList();
arrayOfLists[0] = list1;
Hope it helps.

How do you create a two dimensional collection?

Is there a simple way to create a 2-d collection?
A two-dimensional collection is essentially having lists within a list. For example, to create a 2D ArrayList of strings, you would do something like this:
ArrayList<ArrayList<String>> stringList = new ArrayList<ArrayList<String>>();
To add a new row, you would simply add a new ArrayList:
stringList.add(new ArrayList<String>());
And here's how to add an element to the first row:
stringList.get(0).add("example string");
A 2d collection is a bit abstract... what do you mean?
A double entry array is a 2d collection.
Why don't you use Multimaps from Guava library?
https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained
,
Those collections ads everything that the jdk is missing for dealing with 2d collections.

Sort array and reflect the changes in another array

I have an array of doubles, in Java : arr1 which I want to sort. Most probably the first option would be the utility method Arrays.sort(double[]).
The idea is that I want the same changes (e.g. value at index i is interchanged with value at index j in arr1) to be reflected in another array of integers: arr2 (in the sense that the values at the same indexes are changed also in arr2).
Is there a simple way (a trick) to accomplish this in Java? Or the only way is to implement the sorting algorithm by myself?
UPDATE: I see that people recommend replacing the two arrays with one array of objects containing the 2 values (one from arr1 and one from arr2). Wouldn't this bring some efficiency penalties. In other words, isn't it less efficient to sort an array of objects than an array of primitive types (doubles in this case) ?
The data is completely static. It's large (it fits in memory) but static.
Rather than trying to maintain sorted parallel arrays, a cleaner solution would be to create a class that encapsulates both of your data values, and just have one array of objects.
(But to answer your question, there is no built-in way to do this in Java. Implementing your own sort routine that keeps two arrays sorted based on values in one of them would work for a small amount of data that isn't likely to change, but it would be difficult to maintain.)
One solution which is doesn't impact the performance of sorting, ie still O(nlog(n)) time complexity.
Use a map to store array[i] -> i
Sort the array
Iterate over the sorted array, and for each value, use it as a key for the map to retrieve the original index.
Edit: Raihan comment make me look miserable :(
Try it this way....
- Convert this array into ArrayList using the Arrays.asList()
- Create another List Object Reference Variable and assign the same ArrayList object to it, Now any changes to the first ArrayList will be reflected to the Second ArrayList.
Eg:
double[] array = new double[10];
ArrayList<Double> arList_1 = new ArrayList<Double>(Arrays.asList(array));
ArrayList<Double> arList_2 = arList2;
Now for sorting, there are 2 options:
- Use java.lang.Comparable Interface, if you want to sort it in only 1 way.
- Use java.util.Comparator Interface, if you want to sort it in more than 1 way.
Note sure what are you looking for but one other work around could be like this.
Create a map to maintain the relation between arr1 and arr2 elments
Map<Double, Double> myLocalMap<Double, Double>();
for(int ind=0; indx < arr1.length; indx++){
myLocalMap.put(Double.valueOf(arr1[indx]), Double.valueOf(arr2[indx]));
}
Now sort arr1 as you said:
Arrays.sort(arr1);
Once arr1 is sorted, update arr2 as below:
for(int ind=0; indx < arr1.length; indx++){
arr2[indx] = myLocalMap.get(arr1[indx]).doubleValue();
}

Java generic collections

I start learning the Java generic collection using Deitel Harvey book - but I am facing a difficulty understanding the three line of codes below - Do all of them perform the same operation on by intializing and adding the relevant values of array ( colors ) to the LinkList variable (list1). How does the second method and third method works - I am having a bit difficulty understanding how Arrays can viewed as a list.. As I know arrays are not dynamic data structure, they have fixed sized length, adding/ removing elements on array can not be done on running time comparing to Lists in general.
String[] colors = { "black", "white", "blue", "cyan" };
List< String > list1 = new LinkedList< String >();
// method 1 of initalizing and adding elments to the list
for (String color : colors)
list1.add(color);
// method 2 of initializing and adding elements to the list
List< String > list1 = new LinkedList< String > (Arrays.asList(colors));
// method 3 of initializing and adding elements to the list
List< String > list1 = Arrays.asList(colors);
Please help me understand my queries above, don't judge me as I am still new to this.
Thank you, Sinan
Actually knowledge of generics is not necessary for answering this question.
As you correctly identifier arrays are static in the sense that you can't add elements to them or remove them.
Lists, however, usually allow those operations.
The List returned by Arrays.asList() does have the add/remove methods (otherwise it would not be a valid List). However actually calling those methods will throw an UnsupportedOperationException exactly because you can't actually add elements to an array (for which this List is simply a view/wrapper).
Operations that don't structurally modify the list (i.e. that don't change the number of elements in the list) are entirely possible: set(int, E) works just fine on the List returned by Arrays.asList().
Arrays.asList returns a fixed-size list backed by the specified array.
It is actually a bridge between Array and Collection framework. But returned list write through to the array.
Only your first method does anything to the LinkedList you have initially assigned into list1. The other two assign a new, unrelated list to it. The third option assigns something that isn't a LinkedList, but a special implementation of the List interface backed by your String array. In the third case you won't be able to add/remove elements from the list, but you can iterate over it and update existing slots. Basically, it does what a plain array does, just through the List interface.
Arrays.asList creates a List from an Array. Arrays in general can't be viewed as lists in Java. They can only be wrapped in a list.
So method 2 is used to have a specific list implementation LinkedList in this case.
to Method 2, just check the Api here:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList(java.util.Collection)
For sure, Lists implement the Collections Interface so this Constructor will work here.
to Method 3, just check out the Api here: http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)
Every time you are interested in implementation you can look into certain method. For example, by press Ctrl+left mouse button onto method or class.
// method 2 of initializing and adding elements to the list
List<String> list1 = new LinkedList<String> (Arrays.asList(colors));
This code leads to:
List<String> list1 = new LinkedList<String> (new ArrayList<String>(colors));
In constructor of ArrayList:
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
the actual array is copied to encapsulated private array field(link is copied).
Then in constructor of LinkedList:
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
Every element of passed collection is added to the LinkedList.
if you see the link below
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList%28java.util.Collection%29
you will see the constructor of linked list class which is accepting a collection object as parameter.
Any in your post, the 2nd and 3 rd lines are passing an object of collection class(i.e Arrays.asList is finally giving a List which is a sub class of collection).
So both 2nd and 3rd lines fairly valid implementations.
More over you can observe one more good coding practice in all the 3 lines.
That is
writing code to interceptors than to classes
. (referring
LinkedList
instance with
List
interface)
Always try to refer your classes with interceptors which is a good practice

Categories

Resources