This question already has answers here:
Java - Removing duplicates in an ArrayList
(19 answers)
Closed 7 years ago.
for (int i = 0; i < arrayP.size(); i++) {
if (arrayP.get(i) == What to put here?) {
arrayP.remove(i)
}
}
If I put i+1 it just compares side by side. How can I get it to run through each element?
Element 1 then run through the whole ArrayList. Then element 2 run through ArrayList.
You can use a LinkedHashSet:
list = new ArrayList<>(new LinkedHashSet<>(list));
If the order of elements does not matter, you should use a normal HashSet instead. In fact, if it's logical to do so, you might consider using a Set instead of a List in the first place. Read about the differences between the two and pick the structure that's more appropriate.
try this
Set arrayPSet = new LinkedHashSet(arrayP);
now arrayPSet holds your array removing it's duplicate values, then you can use it, you can
re-assign your list to this set once again, like
arrayP = new ArrayList(arrayPSet);
now duplicates are removes
just make sure to override the equals() and hashCode() methods if arrayP list holds objects created by you
ok, i updated it maybe this works, i didnt try the order issue, but there are TreeSet/Comparators/Comparables solutions , just try this modification first
Related
This question already has answers here:
is collections.sort method only used for List type of collections?
(7 answers)
Closed 6 years ago.
Why can't I Collections.sort my Set<MyType>? My code is below. When I use an ArrayListthis code works perfectly, but when I use any kind of Set, I get this error.
Set<Auto> set = new HashSet<Auto>();
set.add(auto1);
set.add(auto2);
set.add(auto3);
set.add(auto4);
set.add(auto5);
Collections.sort(set, new Comparator<Auto>() {
#Override
public int compare(Auto o1, Auto o2) {
return o1.getMarka().compareTo(o2.getMarka());
}
});
HashSet is not an ordered collection; in other words, it does not contain elements in a certain order.
You can see a HashSet as a bag that contains objects. When you stick your hand in and pull out objects one by one, you don't know in what order you get elements out. You can't sort elements in the bag - because the bag doesn't keep them in the order that you sorted them in.
The order of elements is lost; so sorting a HashSet has no effect (besides the fact that Collections.sort takes a List instead of a Set as Mureinik noticed, so your code doesn't even compile).
If you need the elements in the Set to be in a specific, defined order, then use a different Set implementation, for example TreeSet.
Sets don't have an order, so you cannot order them. As seen in the Javadoc, Collections#sort receives a List, not any Collection.
This question already has answers here:
Why doesn't java.util.Set have get(int index)?
(19 answers)
Closed 6 years ago.
The basic difference between the set and the list is that set wont allow the duplicates
the question is why cant we use original for loop for the set as we use for list
eg: length of set and list is same
for(int i =0 ; i< list.size;i++){
list.get(i);
set.get(i); // here it is throwing an error like get(index ) cant be applied for set
}
but if i use advance for loop(for each) its working
for(Object sample : set){
system.out.println(sample);
}
why is this happening ... is there any operational defference between for loop and for each , set and list ....
any help and suggestion would be useful ... thank you in advance
A Set doesn't have an order, and therefore it doesn't have a get(index) method. Therefore you can't call set.get(i).
The enhanced for loop, on the other hand, works with any class that implements Iterable (as well as with arrays), which includes any Collection. For Sets it will iterate over the elements in an order that depends on the specific Set implementation.
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 7 years ago.
If I do this [quasi-java-code]:
while (loop)
{
localObject = getDataForObject();
globalPublicStaticArrayList<Object>.add(localObject);
}
All the elements in globalPublicStaticArrayList are identical, equal to the last copy of localObject added. I stepped thru the loop in the debugger and saw that as soon as an Object is added, it is copied in to all the elements of the globalPublicStaticArrayList.
The workaround I found is:
while (loop)
{
localObject = getDataForObject();
globalPublicStaticArrayList<Object>.add(new Object(localObject.member1, localObject.member2,...));
}
Has it something to do with pass-by-reference in Java? How come the elements are identical in the first case? Thanks.
Java uses call by value, but here those values are references to objects.
What you are adding to the list is not a copy of the object, but a copy of the reference. Your method returned the same object each time you called it. It probably should return a new object each time, then you wouldn't need this workaround.
globalPublicStaticArrayList<Object>.add(localObject);
here you are passing the localObject reference. You you want a copy of every objects you should create a new object at every iteration
In getDataForObject() may be you are not creating "new" object of return type.
Because of that all objects are pointing to same address.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In Java, how can I test if an Array contains a certain value?
I have an array setup as follows:
Material[] blockedlevel1 = {
Material.mymaterialone, Material.mymaterialtwo
};
How do I see if a Material is in this array?
How about looking for it in the array?
for (Material m : blockedlevel1) {
if (m.equals(searchedMaterial)) { // assuming that equals() was overriden
// found it! do something with it
break;
}
}
If you want an easy way to check if an element is part of a collection you should probably consider a different data-structure like Set (and use contains()). With Array you can only iterate over the elements and compare each one.
How about looking for it using the Arrays class?
See Arrays#binarySearch
Or as someone suggested, turn your array into a List and use the contains() method. Remember that you may have to override the Material#equals method.
This question already has answers here:
Empty an array in Java / processing
(8 answers)
Closed 2 years ago.
I would like to remove all the elements in the String array for instance:
String example[]={"Apple","Orange","Mango","Grape","Cherry"};
Is there any simple to do it,any snippet on it will be helpful.Thanks
If example is not final then a simple reassignment would work:
example = new String[example.length];
This assumes you need the array to remain the same size. If that's not necessary then create an empty array:
example = new String[0];
If it is final then you could null out all the elements:
Arrays.fill( example, null );
See: void Arrays#fill(Object[], Object)
Consider using an ArrayList or similar collection
example = new String[example.length];
If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.
Reassign again. Like example = new String[(size)]
list.clear() is documented for clearing the ArrayList.
list.removeAll() has no documentation at all in Eclipse.
Usually someone uses collections if something frequently changes.
E.g.
List<String> someList = new ArrayList<String>();
// initialize list
someList.add("Mango");
someList.add("....");
// remove all elements
someList.clear();
// empty list
An ArrayList for example uses a backing Array. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.
Just Re-Initialize the array
example = new String[size]
or If it is inside a running loop,Just Re-declare it again,
**for(int i=1;i<=100;i++)
{
String example = new String[size]
//Your code goes here``
}**