7

So I want an arraylist of objects in java.

I have object1.number and object2.number, object3.number, etc... but those objects have other properties besides number, such as name, distance, etc...

So if it was sorting a string in a array it would just be, put a string in a temporal and let the other string take its place... but in an araryList of objects, how can I do it?

Can I just move objects to that position of the array?

Thanks.

4
  • 2
    Does your professor want you to implement the sorting algorithm yourself? Commented Apr 13, 2012 at 17:33
  • what @joncarl says is a good point, if so you need to be looking at bubblesort (its fairly easy to implement but not so fast) Commented Apr 13, 2012 at 17:40
  • Yes, I will implement insertion sort alg. Commented Apr 13, 2012 at 18:24
  • @user1253201: figure out what you need to do with the objects, and look at the methods from List and ArrayList to see what tools are provided to do so. Most sorts rely on a swap method, which is usually a combination of get, remove, and add methods. Commented Nov 19, 2014 at 17:13

6 Answers 6

8

Implement your own comparer:

Arrays.sort(yourArray, new Comparator<YourClass>() {
        @Override
        public int compare(YourClass o1, YourClass o2) {
            //compare object properties
        }
});
Sign up to request clarification or add additional context in comments.

4 Comments

You mean Collections not Arrays, he is dealing with an ArrayList here ?
An ArrayList is a Collection.
Arrays.sort is for arrays, like Object[]. To sort an ArrayList, as mentioned in the question, you would use Collections.sort, as pointed out by @Papa_Jay.
However, this seems to be off-topic, as the OP is apparently supposed to implement a sort algorithm
4

You need to implement the comparable interface

implements Comparable

the method that does the work is

public int compareTo(Object obj)
{
}

Please note that object is often replaced by a full on type because of generic syntax which can be used in the implements statement (shown below).

A full example is here in the tutorial docs hope this helps

A full example (take from the above link is as follows), I have added this just in case the link goes dead at some point

import java.util.*;

public class Name implements Comparable<Name> {
    private final String firstName, lastName;

    public Name(String firstName, String lastName) {
        if (firstName == null || lastName == null)
            throw new NullPointerException();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() { return firstName; }
    public String lastName()  { return lastName;  }

    public boolean equals(Object o) {
        if (o == null || !(o instanceof Name))
            return false;
        Name n = (Name) o;
        return n.firstName.equals(firstName) && n.lastName.equals(lastName);
    }

    public int hashCode() {
        return 31*firstName.hashCode() + lastName.hashCode();
    }

    public String toString() {
    return firstName + " " + lastName;
    }

    public int compareTo(Name n) {
        int lastCmp = lastName.compareTo(n.lastName);
        return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
    }
}

The client code from the article is:

import java.util.*;

public class NameSort {
    public static void main(String[] args) {
        Name nameArray[] = {
            new Name("John", "Smith"),
            new Name("Karl", "Ng"),
            new Name("Jeff", "Smith"),
            new Name("Tom", "Rich")
        };

        List<Name> names = Arrays.asList(nameArray);
        Collections.sort(names);
        System.out.println(names);
    }
}

Comments

0

You need to use comparator for this purpose.

Comments

0

Based on your question, I take it that you are supposed to be implementing the sorting algorithm yourself. If that is the case, you can manipulate the position of elements within an ArrayList, it just works a bit differently than a regular array. Have a look at the add(int index, E element). The index parameter lets you decide where in the ArrayList to add the element.

3 Comments

I think you want to direct him to the set method instead of the add method. the add method, slides elements instead of replacing them.
@ColinD Not necessarily. While you could replace one element with another, you could also remove an element and then place it into its new position, kind of depends a bit on the algorithm.
Unless you are staring with a sorted array and adding new elements, using add() will have hidden performance penalties because it needs to shift all elements that have higher indexes. The same applies for remove(). Using set() is the O(1) way to update entries in the array, which is what you want for sorting.
0

To manipulate the entries of an ArrayList like that of a traditional array, use ArrayList.set(int, E).

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#set%28int,%20E%29

Comments

0

Use to Collections.sort() to sort an ArrayList in Java 8:

Collections.sort(array, new Comparator<Class>() {
    @Override
    public int compare(Class o1, Class o2) {
        //compare object properties
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.