1

I need to add an Object to an ordered ArrayList depending on an attribute inside of the Object. I know how to use the .add method to add the object but I don't know how to search for the right place for it using the compareTo() method. And also I need to remove an Object from the ArrayList if the Object contains a certain String but I cant figure out how to access the Object attributes from the ArrayList.

Realtor Object

/**
 * Constructor for Realtor object using parameter
 * @param readData - array of data from line
 */ 
public Realtor(String[]readData){
    licenseNumber = readData[2];
    firstName = readData[3];
    lastName = readData[4];
    phoneNumber = readData[5];
    commission = Double.parseDouble(readData[6]);
}

RealtorLogImpl

public class RealtorLogImpl {

    private ArrayList<Realtor> realtorList;

     /**
     * Add Realtor object to ordered list
     * @param obj - Realtor object
     */
    public void add(Realtor obj){

       //needs to be added into correct place depending on Realtor licenseNumber
        realtorList.add(obj);
    }

    /**
     * Delete Realtor object from list if license matches
     * and return true if successful
     * @param license
     * @return 
     */
    public boolean remove (String license){
      //need to remove Realtor with specific licenseNumber and return true if successful
    }
Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49
  • `List list = new ArrayList<>();` and `if (list.get(13).length() == 42) {...}` – Joop Eggen May 21 '17 at 21:11
  • What is the type of the objects in the list? If the type is literally just `Object`, what does it mean for an element to "contain" a string? – Daniel Pryden May 21 '17 at 21:12
  • 1
    First, does the Object implement an `.equals()` that has the "certain String"? If so, then the `.remove(object)` will work. Otherwise, you'll need to use an `Iterator`, which will allow you to get the Object, and then use the standard methods to retrieve the value and compare. Second, do you really need an ArrayList (See: [Why Is there No Sorted List](http://stackoverflow.com/questions/8725387/why-is-there-no-sortedlist-in-java)). Best approach is just to add and then sort with an appropriate comparator. – KevinO May 21 '17 at 21:12
  • thank @KevinO I needed to be able to access the values in the Object – Tommy Barrett May 21 '17 at 21:19

3 Answers3

1

I'm assuming you are using java 8. Some of these things have not been implemented in java 7 so keep that in mind.

First, to remove the items I would recommend using the removeif() method on the arraylist. This takes a lambda expression which could be something like x -> x.getString().equals("someString").

Second, You could add the object to the array then simply sort the array afterwards. You would just have to write a comparator to sort it by.

Eli Miller
  • 86
  • 5
1

Here is some basic code; I have no compiler here, so you might find small errors/typos.

I'm sure there are better classes you can use instead of managing your own ordered list.

To insert:

public bool add(Realtor obj) {
    int idx = 0;
    for (Realtor s : realtorList) {
        if (s.licenseNumber.equals(item.licenseNumber)) {
           return false; // Already there
        }
        if (s.licenseNumber.compareTo(item.licenseNumber) > 0) {
           orderedList.add(idx, item);
           return true; // Inserted
        }
        idx++;
    }
    orderedList.add(item);
    return true; // Appended
}

To delete:

public bool deleteItem(String license) {
    int idx = 0;
    for (Realtor s : realtorList) {
        if (s.licenseNumber.equals(license)) {
           realtorList.remove(idx);
           return true; // Removed
        }
    }
    return false; // Not found
}
user3429660
  • 2,420
  • 4
  • 25
  • 41
1

To answer your question check the following snippet (requires Java 8) and adapt on your demand:

public static void main(String[] args) {

    final List<String> list = new ArrayList<>();
    list.add("Element 1");
    list.add("Element 2");
    list.add("Element 3");

    /*
     * Insert at a specific position (add "Element 2.5" between "Element 2" and "Element 3")
     */
    Optional<String> elementToInsertAfter = list.stream().filter(element -> element.equals("Element 2")).findFirst();
    if(elementToInsertAfter.isPresent()) {
        list.set(list.indexOf(elementToInsertAfter.get()) + 1, "Element 2.5");
    }

    /*
     * Remove a particular element (in this case where name equals "Element 2")
     */
    list.removeIf(element -> element.equals("Element 2"));
}

#add(element) just adds an element to the list. In case of an ArrayList it's added at the end. If you want to insert an element at a particular position you need to use #set(index,element)


But instead of inserting your element at a particular position manually you should maybe use a comparator instead. See java.util.List.sort(Comparator<? super E> e)

Marteng
  • 1,179
  • 13
  • 31