2

So I'm a C++ programmer student, and I'm starting to learn Java, and I would like to read a class called Candidate with two string values (Name and ID), and I would like to store these Candidates in a container.

What would be the best container to use in this situation, and what could I use to store these values while sorting them by Name.

Since I'm used to STL library, I was thinking about something like a vector or a list.

Thanks!

magalenyo
  • 275
  • 6
  • 17
  • 3
    Unless you need to allow duplicates, I'd probably use a `TreeSet`. – Elliott Frisch Dec 21 '16 at 18:41
  • 1
    Please clarify the use case. Is the sorting the salient feature? You mentioned STL vector or list which are not sorted by default. – shiri Dec 21 '16 at 18:46
  • This question has almost certainly been answered a few times before, so hunt around on Stack Overflow for questions about sorting custom types. A `TreeSet` with a custom `Comparator` fed to its constructor will do the job, and there are bound to be answers here on SO which give example code for this. – Bobulous Dec 21 '16 at 18:47
  • 1
    @Bobulous The thing is, I've seen a lot of people with different data structures, sorted sets, linked lists, tree sets, sorted map, array list, etc. What I'm looking for is the best one to sort while reading a custom class. – magalenyo Dec 21 '16 at 18:50
  • 1
    @magalenyo, the custom class doesn't matter in Java. Containers can use any class. – shiri Dec 21 '16 at 18:52
  • If any of the solutions below answers your question, please accept it. – shiri Dec 22 '16 at 15:22

6 Answers6

3

What exactly is the use case you are looking for? The best container would depend on whether your usage including insertions, removals, reading in order or not, etc.

If you're just interested in Java equivalents to the C++ STL classes, the Java equivalent of std::vector is ArrayList (see Equivalent of std::vector in Java? ). They are both dynamic arrays.

If I'm not mistaken, the Java equivalent of std::list is LinkedList.

This answer gives a nice overview on the topic: Linked List vs Vector

If you're looking for a list that was inserted and deleted while maintaining sorted order, you'd likely be best of with TreeSet as mentioned in the comments above.

Community
  • 1
  • 1
shiri
  • 745
  • 6
  • 24
  • This will not sort the `Candidate` objects by the value of the name they contain. – Bobulous Dec 21 '16 at 18:45
  • Correct, edited. However, the question is ambiguous since it is discussing STL classes that are also unsorted. – shiri Dec 21 '16 at 18:45
1

You probably are best served by using a PriorityQueue with this constructor https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#PriorityQueue(int,%20java.util.Comparator)

Then you can simply instantiate it via like:

new PriorityQueue<Candidate>(10, new Comparator<Candidate>() {
            @Override
            public int compare(final Candidate o1, final Candidate o2) {
                return Candidate.getName().compareTo(o2.getName());
            }
        });

10 would just be an example capacity here, you can choose whatever fits your use case.

The priority queue will automatically order your Candidate objects according to their name on every insert since you specified a Comparator that does so for you.

Armin Braun
  • 3,645
  • 1
  • 17
  • 33
  • 1
    Out of curiosity, why do you recommend a `PriorityQueue` over a `TreeSet`? – Bobulous Dec 22 '16 at 01:11
  • @Bobulous `TreeSet`, being a `Set` would have been a less general answer. Though speaking of "Candidates" I guess it's find to assume no duplicates, still why introduce the uniqueness constraint when you don't have to and it's not in the problem description :) ? – Armin Braun Dec 22 '16 at 06:39
  • @ArminBraun Thanks for your answer, although I've finally decided to use a TreeSet basically because I'm more used to that, thanks! – magalenyo Dec 23 '16 at 11:59
0

You can use a TreeSet to insert into a container that is maintained in a sorted order. However, this is a set, not a list, so you cannot access by index.

0

A simple Approach:

//Declare your Candidate class as:

  class Candidate
  {
      int id;
      String name;

      Candidate(int id,String name)
      {
         this.id=id;
          this.name=name;
      }

      public int getId()
      {
            return this.id;
      }

      public String getName()
      {
             return this.Name;
       }
  }

 class Main
 {
      public static void main(String args[])
      {
          ArrayList<Candidate> al=new ArrayList<Candidate>();
          al.add(new Candidate(1,"ABC"));
          al.add(new Candidate(2,"XYZ"));
          al.add(new Candidate(3,"PQR"));

          Collections.sort(al,new SortByName());

          System.out.println(al);

       }
  }

//Declare a Comparator to sort by Name

  class SortByName implements Comparator<Candidate>
  {
        public int compare(Candidate c1,Candidate c2)
        {
            return c1.getName().compareTo(c2.getName());
         }
   }

// As you have posted in your question that you are beginner to java, and as per your requirement you want to have container to store objects of class, and then sort them by thier field name. Hence, I have used ArrayList from Collections class which is very simple to use and learn for beginner's like, I would reckon you to go through some basic concept's of arraylist class,Comparator,Collections method etc.

Manish Sakpal
  • 299
  • 1
  • 9
  • The OP wants to keep a sorted collection by student name as variant of the collection tiself. he doesn't want to sort it each time before an performing operation any operation on that collection. However since he mentioned he want to use somethig similar C++11's vector/list, it could lead to confusion. here is +1 for being a gentelman. you don't deserve that downvote. – Aviv Dec 23 '16 at 21:02
0

Thank you all guys for all the answers, after a research of the proposals you've granted me, I've finally decided to use a TreeSet just because I found that was the most useful to me in this case. Thanks again!

magalenyo
  • 275
  • 6
  • 17
-5

Take a look at SortedMap and SortedList.

Nikolay K
  • 3,770
  • 3
  • 25
  • 37
arcy
  • 12,845
  • 12
  • 58
  • 103
  • 2
    A "SortedList", which doesn't exist in core Java, goes against the concept of a `List`. See http://stackoverflow.com/questions/8725387/why-is-there-no-sortedlist-in-java – Zircon Dec 21 '16 at 18:42
  • My mistake. Was thinking of a TreeSet, had a brain burp. – arcy Dec 21 '16 at 19:07
  • The question was `What would be the best container to use in this situation, and what could I use to store these values while sorting them by Name.` The TreeSet, which was what I meant to say as indicated in the comment correcting my mistake, and SortedMap, which I did say, are answers to that question. This is a person familiar with programming but new to the language, all they're liable to need is a pointer to the right classes. – arcy Dec 22 '16 at 03:05