ArrayList does not encapsulate a good method of removing weight, for example, for a [2, 5, 2, 3, 2, 4] ArrayList, I want to remove the duplicated elements,
I do not want to put the statement also so long, do not want to use for the method of the loop to heavy, then you can consider the ArrayList into a temporary hashset, and then the temporary HashSet converted back to ArrayList, because the elements of the hashset inside is not repeatable! As for what is ArrayList and HashSet, in the "Detailed Java Collections class" has been made very clear, here no longer repeat.
You can write this:
hashset<integer> hashset_temp = new hashset<integer> (ArrayList);
ArrayList = new arraylist<integer> (hashset_temp);
can also write more concise, even the temporary hashset_temp variables are not:
arraylist = new Arraylist<integer> (new Hashset<integer> (ArrayList));
after that, the ArrayList elements become [2, 3, 4, 5]
Here are two ways to share the weight of ArrayList
//Go repeat method one
Private ArrayList Removeduplicatenum (ArrayList list)
{
list. Sort ();
for (int i = 0; i < list. Count-1; i++)
{
if (list[i]. Equals (List[i + 1]))
{
list. RemoveAt (i);//Go to repeat item
i--
}
}
return list;
}
To repeat Method two
Private ArrayList Removesame (ArrayList list)
{
//The sentence written above is superfluous, this is the final for
(int i = 0; i < list. Count-1; i++)
{for
(int j = i + 1; j < list.) Count; J + +)
{
if (list[i]. Equals (List[j]))
{
list. RemoveAt (j);
j--
}
}} return list;
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.