简体   繁体   中英

Java Object Reference Tasks

I need help to figure out a method on how to add elements to my array list. Once added i would like to have it show true or false if the element was added previously, if not then have it show true as in successfully added new Disc. This is a portion of my code so far.

public class MediaArchive 
{
private String name ;
private String owner ;
private ArrayList<Disc> list;

//Constructor
public MedieArkiv(String name, String owner) {
    this.name = name;
    this.owner = name;
    list = new ArrayList<Disc>();
}

//Method for adding a new "Disc" to the ArrayList.
public void addDisc(Disc newDisc) { 
    list.add(newDisc);
}

So my question is, how do i make a method that can add "new Discs" to my array list? And save them as parameters so the list knows if they are added or not by using ture or false to show it. Sidenote: I am learning this through BlueJ, and am still very fresh at the language.

If you are trying to get a list of unique Disc values, you should first override the equals and hashCode methods of Disc . This allows you to determine whether two different instances of Disc should be considered to have equal values.

Then, replace ArrayList with LinkedHashSet : LinkedHashSet is an implementation of Set (which, by contract, forbids duplicate values) but that also preserves insertion order - so it's a bit like a List without duplicates.

Now LinkedHashSet.add(Disc) would return true if the element is "new", and false if it was already present.

Implementing Collection.add , List.add returns:

true if this collection changed as a result of the call

... (see API ).

Note that as mentioned by Andy Turner this will always return true for ArrayList (if an Exception is not being thrown by add ).

You could also have a Set instead, and implement equals and hashCode in your Disc class, in case your check is required to ensure no duplicates are being added.

The Set.add method returns:

true if this set did not already contain the specified element

... (see API ).

ArrayList has Contains method, you need to pass on the argument so, that it will return true if the value is already added else it will return false.

In your case

if(list.contains(newDisc))   
{    
//Element already added
}   
else
{
list.add(newDisc);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM