I want to know the shortcut for doing this :
class{ ArrayList a1=new ArrayList();
ArrayList a2=new ArrayList();
ArrayList a3=new ArrayList();
.....& so on
}
So instead of writing each reference, how can I write an array of references 'with ArrayList' ?
you can use `List<ArrayList> list = new ArrayList<ArrayList>();`. In this you can add any number of `ArrayList` Objects to `list` reference.
Find the below :
List<ArrayList> list = new ArrayList<ArrayList>();
list.add(new ArrayList());
list.add(new ArrayList());
list.add(new ArrayList());
list.add(new ArrayList());
// ....
list hold ArrayList references in inserted order. You can access the ArrayList using index which zero based.
// to access the ArrayList reference.
ArrayList a1 = list.get(0);
Use an array of ArrayList. And loop.
ArrayList a1, a2, ... , a100;
ArrayList[] arrayLists = new ArrayList[100];
for (ArrayList arrayList : arrayLists) {
arrayList = new ArrayList();
}
But creating different references array is not a good design.
For example you can create array list array like below:
ArrayList[] a = new ArrayList[4];
Before implementing this you clear with your requirement , why you need to create these many references.
And also while creating ArrayList it's better to use reference creation like below:
List<String> a = new ArrayList<String>();
Always use generics while working on JAVA collections.
For your requirement to store word and it's permutations, I would suggest below process:
Step1: Create WordPermutations class
public Class WordPermutations{
public string word;
public ArrayList<String> permutations = new ArrayList<String>();
public void setWord(String word){
this.word = word;
}
public void setPermutations(ArrayList<string> permutations){
this.permutations = permutations;
}
public String getWord(){
return this.word;
}
public ArrayList<String> getPermuatations(){
return this.permuations;
}
}
Step2: Use this class to create your arrayList objects like below:
Class MainPermutation{
public static void main(String args[]){
// your code to get all your words and their permutations
// Now add them like below
ArrayList<WordPermutations> words = new ArrayList<WordPermutations>();
//your loop to iterate words and their permutations
for (int i=0;i<words.length;i++){
WordPermutations wordP = new WordPermutations();
wordP.setWord(word); //String word
wordP.setPermutations(permutations); //arraylist of permutations
words.add(wordP); //adding your word and it's permutations to class
}
}
}
Step3: Now read your arrayList array accordingly
with above process you can store n number of words.
Hope it helps you.
Related
I want to create one sorted list out of my original list - without the Collections.sort(list) call changing the original list. So that I have one list unsorted and one being sorted - out of the same list.
Take a look at this code:
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList();
list.add(5);
list.add(8);
list.add(3);
list.add(6);
System.out.println("Before method list is");
System.out.println(list);
ArrayList<Integer> theReturnedList = sorted(list);
System.out.println("After it is");
System.out.println(list);
}
private static ArrayList<Integer> sorted(ArrayList<Integer> list){
ArrayList<Integer> returnList = list;
Collections.sort(returnList);
return returnList;
}
The list object gets sorted - even though I am not calling the Collection.sort() method onto it. How can I avoid it?
Beacuse I thought this would happen...
public static void main(String[] args) {
String original = "I am an object created in main";
String theChangedObject = change(original);
System.out.println(original);
}
private static String change(String string){
String changed = string;
changed = "I was changed";
return changed;
}
The object orginal stays the same.
Your problem is a misunderstanding of how references work. Let's take a look at the method:
private static ArrayList<Integer> sorted(ArrayList<Integer> list){
ArrayList<Integer> returnList = list;
Collections.sort(returnList);
return returnList;
}
The line ArrayList<Integer> returnList = list; does not copy the list. It copies the reference to the list. What this means is that returnList and list will both refer to the same list. Changes in one will affect the other, because they are actually just different names for the same thing.
What you want to do is to make a brand new list containing the same values, which can be done with
ArrayList<Integer> returnList = new ArrayList<>();
returnList.addAll(list);
There is also a convenient ArrayList constructor that does this in one step:
ArrayList<Integer> returnList = new ArrayList<>(list);
Changes to returnList will not affect list because they are now two completely independent lists that just happen to contain the same values.
In your sorted method you are still calling Collection.sort on the original list. To avoid this you could create a shallow copy and return that e.g.
private static ArrayList<Integer> sorted(ArrayList<Integer> list){
ArrayList<Integer> returnList = new ArrayList<>(list);
Collections.sort(returnList);
return returnList;
}
On this line:
ArrayList<Integer> returnList = list;
you are just creating another reference to the same list (Object) in your sorted method and any change that you apply to it using this new reference will be reflected in you original reference because they point to the same object. You can do this to create a new list:
private static ArrayList<Integer> sorted(ArrayList<Integer> list){
ArrayList<Integer> returnList = new ArrayList<>(list); // the new keyword creates a new object on the memory heap
Collections.sort(returnList);
return returnList;
}
This time we are creating another ArrayList Object with the elements of you original list. This way the original list won't change when you sort the newer.
This behaviour doesn't apply on Immutable Objects like String or LocalDateTime. These cannot change their state after being created and instead return a new copy with the changes applied.
you can use Stream api
List<Integer> list = Arrays.asList(5,8,3,6);
List<Integer> newList = list.stream().sorted().collect(Collectors.toList());
The stream api offers several methods to work with collections immutably. This is the recommended way if you are using Java 8 or later.
So when I insert an Arraylist A into an Arraylist constructor I expect a new Arraylist object B created with the same set of objects as A. In my case I have
Arraylist<Arraylist<Integer>> powerSet
Arraylist<Arraylist<Integer>> OG
Both powerSet and OG seem to share the same reference despite OG being constructed from powerSet like this:
ArrayList<ArrayList<Integer>> OG = new ArrayList<>(powerSet);
Here is the full code:
public static ArrayList<ArrayList<Integer>> generatePower (ArrayList<Integer> s){
ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>();
generatePower(s,powerSet);
return powerSet;
}
public static void generatePower(ArrayList<Integer> s,ArrayList<ArrayList<Integer>> powerSet ){
if(s.size()==0){
powerSet.add(s);
return;
}
else{
int temp = s.remove(0);
generatePower(s,powerSet);
ArrayList<ArrayList<Integer>> OG = new ArrayList<>(powerSet);
for(ArrayList<Integer> el: OG){
el.add(temp); //for some reason any changes I make to OG here is
//reflected in the powerSet
}
powerSet.addAll(OG);
}
}
Why do OG and powerSet have the same reference and how do I make OG be a new arraylist containing all of powerSet's elements without have OG share powerSet's reference
The ArrayList constructor doesn't clone elements; it just copies references over. Here's one way to make a deep copy using streams
List<List<Integer>> copy = powerSet.stream()
.map(ArrayList::new)
.collect(Collectors.toList());
ArrayList<ArrayList<Integer>> OG = new ArrayList<>(powerSet);
this line pass all elements (copy references) stored in powerSet to OG.
It's work in the same way like example:
List<User> usersList_1 = Arrays.asList(user1, user2, user3);
List<User> usersList_2 = new ArrayList(userList_1);
user1.setName("John");
userList_2.get(0).getName();
output: John
I have an array and i want to compare the first element of this array with every element of another array in an Arraylist?
The purpose of doing this is to check whether or not the first element of the array exist in the another array of an Arraylist.
is this possible?
if yes, how?
List<List<String>> arrayst = new ArrayList<List<String>>();
List<List<String>> arrayqu = new ArrayList<List<String>>();
List<List<String>> arrayya = new ArrayList<List<String>>();
List<String> items = Arrays.asList(line.split(":",-1));
// i want to compare 1st element of items with 3 of the list above.
Create a different class and try something like this -
public class StackOverflow {
public void compare(List<String> items, List<List<String>> list){
String itemToBeCompared=items.get(0);
for(List<String> l:list){
if(l.contains(itemToBeCompared)){
System.out.println("Its Present");
}
else{
System.out.println("Not Present");
}
}
}
}
Then in the main method do something like this -
List<List<String>> arrayst = new ArrayList<List<String>>();
List<List<String>> arrayqu = new ArrayList<List<String>>();
List<List<String>> arrayya = new ArrayList<List<String>>();
List<String> items = Arrays.asList(line.split(":",-1));
StackOverflow st=new StackOverflow();
st.compare(items,arrayst);
st.compare(items,arrayqu);
st.compare(items,arrayya);
Hope this helps! Please let me know if this works for you.
I have an arraylist of an arraylist declared like
ArrayList<ArrayList<Integer>> bigList = new ArrayList<ArrayList<Integer>>();
I would then add to this bigList by bigList.add(arraylist).
I then have a class that takes ArrayList<Integer> as a construcor parameter. My question is how do I send a certain ArrayList in bigList to this class as a constructor parameter? I can iterate through my bigList with
for(ArrayList<Integer> list : bigList) {
for(Integer num : list)
System.out.println(num);
}
but I have not been able to send a whole ArrayList element to another class. Thanks a bunch.
You can select an ArrayList at a particular index and pass it to a constructor as follows:
int index = 2; // the index of the list you want to pass to the constructor
MyNewObject newObject = new MyNewObject(bigList.get(index));
Have you tried:
List<SomeClass> sList = new ArrayList<>();
for(ArrayList<Integer> list : bigList) {
sList.add(new SomeClass(list));
}
This would work fine if you are looking to iterate though all lists in bigList and construct new instances from all of them. Alternatively, if you just want to create one such object for a specific list at index "i" of bigList:
SomeClass s = new SomeClass(bigList.get(i));
is it possible to run the following code with logic in 6th line ?
public class arraylist{
public static void main(String args{}){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible?
}
Iterator it=al1.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
Change al.add(s); by al.addAll(Arrays.asList(s)); and you should be all set.
Try the following:
ArrayList<String> al = new ArrayList<String>(Arrays.asList(s));
You have the answer in your question.
When you say you want to convert array asList
As many have already suggested, use Arrays.asList. But before the code would work, you would still need to fix the formatting as you have code outside the main method that is referring to your array list variable in the main method.
public static void main(String[] args){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(Arrays.asList(s));
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible ?
Yes. It is possible.You can add any object to ArrayList including array object.
But while iterating the ArrayList object you will get an array element by calling it.next().So output will be String representation of array object not the array elements
So try this
String s[]={"Sam","Tom","Jerry"};
ArrayList<String> al=Arrays.asList(s);
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
I did the following to store arrays in a ArrayList. The declaration is:
ArrayList<String[]> training = new ArrayList<String[]>();
To input the words and add it:
String input = sc.nextLine();
s1 = input.split(" ");
training.add(s1);
The split method splits the string with spaces and stores each word in the respective index in array s1 which was already declared with the size required for the program."sc" is the scanner object already declared.The individual arrays can be accessed by using:
String s4[] = training.get(index_of_array_you_want);
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList arr=new ArrayList(Arrays.asList(array))