0

Like the title says, I have an ArrayList in java with Objects. The Objects are basically room types in a hotel. they all have a typename, amount of beds etc. Now my problem is, I need to find two objects with the same value for the typename field. I got as far as looping through the list with a for loop but cant figure out how to continue. Here's my code:

import java.util.ArrayList;

public class KamerType {

    private String typeNaam;
    private int aantalBedden;
    private double prijsPerNacht;

    public KamerType(String tN, int aB, double pPN){
        typeNaam = tN;
        aantalBedden = aB;
        prijsPerNacht = pPN;
    }

    public String toString(){
        String s = "De kamer van type " + typeNaam + " heeft " +     aantalBedden + " bedden en kost " + prijsPerNacht + " euro.";
        return s;
    }

    public static void main(String a[]){
        ArrayList<KamerType> kamertypes = new ArrayList<KamerType>();
        KamerType k1 = new KamerType("Standaard", 2, 60.0);
        kamertypes.add(k1);
        KamerType k2 = new KamerType("DeLuxe", 2, 85.0);
        kamertypes.add(k2);
        KamerType k3 = new KamerType("DeLuxe", 4, 125.0);
        kamertypes.add(k3);
        KamerType k4 = new KamerType("Hiker", 2, 35.0);
        kamertypes.add(k4);

        System.out.println("Dit zijn de kamertypen:");
        for(KamerType KT : kamertypes){
            System.out.println(KT.toString());
        }

        System.out.println("\nTesten op zelfde typenaam:");

        for(KamerType KT : kamertypes){
            /*if(kamertypes.get(1).typeNaam == KT.typeNaam){
                ???
            }*/
        }

    } // end of main

}// end of class

Any help is appreciated :)

Edit: two working answers have been given by npinti and Djorde Ivanovic, npinti gave a more guideline-ish answer. Thanks alot guys :)

3
  • You just want to find it? What do you want to do with it when you find it? Commented Jan 28, 2015 at 14:13
  • @DjordjeIvanovic print something to the console Commented Jan 28, 2015 at 14:17
  • Your fields are private so first of all you need to use getter for the typeNaam. Next during iteration you should add room to the HashMap based on the typeNaam. If during adding room to the map you notice that value for given key exists it means that value you adding and value inside map have the same typeNaam. Commented Jan 28, 2015 at 14:19

4 Answers 4

2

Since this sounds like home work, I'll try and provide some basic guidelines as opposed to solutions.

The most basic (albeit less efficient) way would be to do a nest loop and compare the rooms:

(I assume that if an object has all 3 fields which are the same, then, I am referencing the same object. Thus, this part: AND (r1.aantalBedden != r2.aantalBedden)) AND (r1.prijsPerNacht != r2.prijsPerNacht) would help me avoid saying that I have a duplicate (when comparing the same object).

for each KamerType r1 in kamertypes
    for each KamerType r2 in kamertypes
        if(((r1.typeNaam.equals(r2.typeNaam)) AND (r1.aantalBedden != r2.aantalBedden)) AND (r1.prijsPerNacht != r2.prijsPerNacht))
            print("We have duplicates");

An alternative, more standard (if you will) way of doing it would be to:

  1. Make your KamerType class override the equals method, and change it such that two KamerType objects are the same if they have the same typeNaam field.

  2. Use a data structure such as a Set (which does not allow duplicates) and place your KamerType objects in it. This will internally invoke the equals method and if it yields true, then, it will nod add the room to the set, thus allowing you to end up with a list of KamerType objects which are unique.

As a minor note, I also noticed this in your code: if(kamertypes.get(1).typeNaam == KT.typeNaam). In Java, string comparison is done through the equals method, so that should become if(kamertypes.get(1).typeNaam.equals(KT.typeNaam)).

EDIT: As per your comment, the second approach would allow you to solve the problem by going once through the list. There would also be a third approach to solve this problem however I think that it is the worst part of both solutions I provided above (slightly complicated to implement, and the execution might take longer).

  1. Make your KamerType class implement the Comparable interface. This will force you to implement the compareTo()* method. In your implementation, you simply (in this case at least) compare the typeNaam. Then sort the list.

  2. Once that you will have your sorted list, start from the second element of your list and compare it with the previous one. Since your list is sorted by typeNaam, any two objects which have the same typeNaam field will be exactly next to each other in your list, so you would be able to find duplicates without having a O^2 time complexity.

    • This will allow you to call Collections.sort() and make it sort your collection in a way you want it.
Sign up to request clarification or add additional context in comments.

5 Comments

Yes this is indeed a school assignment and thank you for staying with guidelines ;p I have to find two objects with the same value for ONE field: the typename. i do not know where the duplicates are in the arraylist and they have to be in an arraylist.
@T0aster: If you must use ArrayLists, then the first approach is what you must use. If you just care about the one field, then the first example I provided should do the trick for you since the other two fields are used just to ensure that I am not checking the same object.
Tried it and it works. Still though, can it really not be done with just one for loop?
@T0aster: I have included a third approach in my answer. Something along the third option is used when you need to process vast amounts of data and you cannot use a database for instance. Since you do not seem to have millions of rooms, I would recommend against the 3rd approach for this case, but I think it would be a useful exercise for you to try out.
Thanks for giving a third option but im gnna stay with for equals for now. Im pretty sure we will get more explanation and if not i will ask for it to my teacher. Thanks again for everything!
0

to compare strings, use 'equals' function instead of '=='

like this

if(kamertypes.get(1).typeNaam.equals(KT.typeNaam))

1 Comment

the problem here is that i dont know in advance where the duplicates are
0

First create a getter method for your field:

public String getTypeNaam() {
    return typeNaam;
}

Then you can compare the two values:

if(kt1.getTypeNaam().equals(kt2.getTypeNaam)) {
     // Name of kt1 and kt2 is identical
}

If you want to compare each object which each other, use nested loops:

for(KamerType kt1 : kamertypes){
    for(KamerType kt2 : kamertypes) {
         if(kt1.getTypeNaam().equals(kt2.getTypeNaam)) {
              // Name of kt1 and kt2 is identical
         }
    }
}

Be aware that this also finds two identical objects because they of course have the same name. You can exclude those by adding the condition kt1 != k2 to your if.

Comments

0

Here is what you need. First add getter for your private fields. I used loops with i and j to avoid duplicating.

 for(int j = 0;j<kamertypes.size();j++){
            for(int i = j+1;i<kamertypes.size();i++){
                if(kamertypes.get(j).getTypeNaam().equals(kamertypes.get(i).getTypeNaam()) && i!=j){
                    System.out.println(kamertypes.get(j) + "    and "  +kamertypes.get(i));
                }
            }

        }

3 Comments

Looks promising, gnna try it now.
It works but cant it be done with just one for loop? because this way two iterations of the array are checked against eachother right?
Hardly, since you need to compare every object with all other objects in list.

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.