How to remove Object in Java List? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have one existing code, where the written line is
private Rule[] ruleList;
Where Rule is a CLASS.
I want to remove all Rules which are added here in ruleList.
but as I click right it shows like this
If it is a List, how can I delete these rules from ruleList?
Thanks

The ruleList is an array and not a List. Thus you will not find a clear method.
But you can use
Arrays.fill(ruleList, null);

You have an array and not a list. Solution :
ruleList = new Rule[ruleList.length];

To remove all items from a List use clear()
If you want to remove all items in an array from a List use the remove method.
Example
public class Rules {
public static void main(String[] args) {
Rule[] rules = new Rule[2];
rules[0] = new Rules.Rule();
rules[1] = new Rules.Rule();
//Scenario 1
List<Rule> ruleList = new ArrayList<Rule>();
ruleList.add(Arrays.asList(rules)); //adds array to list
ruleList.clear(); //removes all items from List
//Scenario2
ruleList.add(Arrays.asList(rules)); //adds array to list
ruleList.remove(Arrays.asList(rules)); //remove all rules in [] form list
//Scenario3
Arrays.fill(rules, null); //removes all elements in array
}
static class Rule{
}
}
It is important to determine whether you are using a List or an Array. The provided code depicts an array, however the verbiage keeps referring to a List.
If you actually have a List and want to remove all elements see Scenario 1 in the example.
If you actually have a List and want to remove all elements in the array from the List see Scenario 2 in the example.
If you actually have array and want to remove all elements from the array see Scenario 3 in the example.

Related

More efficient way to get the intersection between 2 or more nested ArrayLists [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
If I had, say separate 3 nested ArrayLists of Strings, i.e., ArrayList<ArrayList<String>>:
What is the most efficient way of finding their intersection (common elements)?
Are there other data structures to replace the nested ArrayLists structure that could improve the efficiency of finding their intersection? (e.g. The first structure I can think of is using a Set, but I would like to see if there are other suggestions for this.)
Thanks in advance!
The intersection of two lists is done using the retainAll() method.
It update the list, so if you don't want that, you should copy the list first.
If you have more than 2 lists, you copy the first and then call retainAll() for each of the remaining lists.
ArrayList<ArrayList<String>> lists = ...
List<String> intersection = new ArrayList<>(lists.get(0));
for (List<String> list : lists.subList(1, lists.size()))
intersection.retainAll(list);
However performance will be a bad O(n*m), where n and m are the sizes of the two largest lists.
That is because retainAll() does a contains() against the list given in the parameter, which is a sequential search, for each element in the intersection list.
Performance can be improved to O(n), where n is the largest list, by converting the lists to sets.
List<String> intersection = new ArrayList<>(lists.get(0));
for (List<String> list : lists.subList(1, lists.size()))
intersection.retainAll(new HashSet<>(list));
In Java 8+, the for loop can be simplified to one of these:
lists.subList(1, lists.size()).stream().map(HashSet::new).forEach(intersection::retainAll);
lists.subList(1, lists.size()).forEach(list -> intersection.retainAll(new HashSet<>(list)));
i would use the list.retainAll method as in
private ArrayList<String> getIntersection(ArrayList<ArrayList<String>> lists) {
if(null == lists || lists.isEmpty()) {
return null;
}
ArrayList<String> intersection = lists.get(0);
lists.forEach(intersection::retainAll);
return intersection;
}

Adding An ArrayList<String> to ArrayList<ArrayList<String>> [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm currently attempting to save an ArrayList of Strings to an ArrayList of Arrays of Strings. Below code shows the basics of what I'm attempting.
ArrayList<ArrayList<String>> groupCollection= new ArrayList<ArrayList<String>>();
ArrayList<String> m_listItems = new ArrayList<String>();
groupCollection.add(m_listItems);
I add Strings to m_listItems using the same .add() functionality and it adds string correctly.
But in the debugger, when I attempt to add m_listItems (that does infact have an array of values in it) into the first index of groupCollection, it adds a null array into the first index.
Your code is fine, that's not a null, just an empty array list!
You need to add objects to your m_listitems list, m_listitems.add("foo"); execute you groupCollection.add(m_listItems); method and you should see a different result.
Answers above are certainly correct.
Just to add few details.
We created a ArrayList of ArrayList of String named groupCollection. And ArrayList named m_listItems.
Create another ArrayList for example n_ListItems. And add strings to both ArrayList.
ArrayList<String> m_listItems = new ArrayList<String>();
m_listItems.add("Hello");
m_listItems.add("Welcome");
ArrayList<String> n_listItems = new ArrayList<String>();
n_listItems.add("Hi!");
n_listItems.add("Wel..");
n_listItems.add("Come..");
Add both lists to groupCollection.
ArrayList<ArrayList<String>> groupCollection= new ArrayList<ArrayList<String>>();
groupCollection.add(m_listItems);
groupCollection.add(n_listItems);
We have added 2 arraylists to our ArrayList of ArrayList of String. To see the working of this program, I am displaying list using Iterator.
Iterator<ArrayList<String>> iterator = groupCollection.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
This will give output as follows.
[Hello, Welcome]
[Hi!, Wel.., Come..]
Now we can clearly see the way this program is working.

Java .set for lists? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am learning the basics of lists in Java and I was wondering what .set did I already understand the concept of .add however I cant really find anything about .set and its relation to lists other then examples. I would really appreciate if someone could give me some insight on this command.
Set will specify the position in the List for the object you are storing. The List inteface represents an ordered collection of objects so the position is able to be changed. Similar to an array.
Look at the section Positional Access and Search Operators on: http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
set(pos, elem) as per the Java docs:
Replaces the element at the specified position in this list with the
specified element.
This means that you can change the stored element/reference at a specific position in the list, as long as the position is within the allowed position bounds. So, if you have 3 elements within the list already, you can specify position in set(position,element) to a value between 0 and 2, inclusive. Here is a simple demonstration of how you can replace the 1th (so really the 2nd, as it's 0-indexed) element in an ArrayList and then set it back to the original value:
import java.util.ArrayList;
public class Foo {
public static void main(String[] args) throws Exception {
ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(1);
foo.add(2);
foo.add(3);
System.out.println(foo);
foo.set(1, 999);
System.out.println(foo);
foo.set(1, 1);
System.out.println(foo);
}
}
But really, this is explained more than clearly enough in the Java doc for List, so as others have said: read it and try it out next time.

Finding permutations of a linked list [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a linked list that I'm trying to generate all permutations of.
The link list is made of ListNode objects that simply contain an integer and a reference to the next ListNode.
I'm trying to do something like this:
public void generatePermutatoins(ListNode head) {
//code that generates permutations
//let's say it finds a permutation and stores the entire list in
//ListNode singlePermutation;
//printList(singlePermutation);
}
I'm wondering if there is a recursive solution as well? I'm quite stuck on any solution, though.
Yes you can do it recursively easily if you define your problem correctly.
You have a linked list and a reference to the head of the list. You have a function that recursively creates all the permutations of all elements after head.
When you get the result you go over each permutation and you add head in each position generating the last permutation.
If you haven't figured it out this was your recursive function. The following is a skeleton/pseudo code in Java to get you started. The addEachPosition(permutation, node.value); adds the value in all possible positions in the list
public List<List<Integer>> getPermutations(ListNode currentNode) {
if(currentNode == null) {
return new ArrayList<ListNode>();
}
List<List<Integer>> nextPermutations = getPermutations(currentNode.next);
addToPermutations(currentNode, nextPermutations);
return nextPermutations;
}
public void addToPermutations(ListNode node, List<List<Integer>> permutations) {
for(List<Integer> permutation:permutations) {
addEachPosition(permutation, node.value);
}
}
This non-recursive (iterative) implementation might be helpful: Collections2.permutations.

References mixup in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
class blabla extends JPanel
{
public blabla()
{
//code
}
}
class Main
{
public static void main(String[] args)
{
JPanel b;
ArrayList<blabla> c;
blabla a = new blabla();
b = new JPanel();
c = new ArrayList<blabla>();
b.add(a);
c.add(a);
blabla d = (blabla) b.getComponent(0);
System.out.println(c.indexOf(d));
}
}
Are ArrayList a and JPanel a same objects?
What should be the codes output?
This answer is based upon what you mentioned in the question when no code snippet was provided and quetion was...
I have created a component instance, drawn it onto the screen, and added it to an ArrayList.
I'm accessing it by referencing to the drawn one using it's children (getParent() method). However, when I then pass this reference to ArrayLists indexOf(); method, it returns -1.
I suppose that means that the component does not exist in the ArrayList.
Is this what should happen, or did I probably mess something up in my program? I'm NOT providing you with a SSCCE, I'm not asking you to do any coding, just to tell me if this is normal Java behavior...
Here goes the my response
The javadoc of indexOf() says...
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
As you can see this depends on the equals() implementation for you component. Check your implementation as that holds the key of retrieving the value from list.
Alright here goes the answer for your modified question...
Are ArrayList a and JPanel a same objects?
No. But they contain the same object of class blabla.
What should be the codes output?
The output is
0
which is right as you placed the same component in the JPanel and ArrayList and 0 is the index of element.

Categories