A brief introduction to the use of ArrayList in Java _java

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.