Josh
Josh

Reputation: 519

About lists in java

I am studying lists in Java now. I am having trouble comparing two lists with one another. What I am trying to do is return true if both lists have the same name, but it keeps returning false. In my class examples DVD1 and DVD3 should both have the same name. A DVD is a CD and an IBook. So DVD1 is a CD1, which name is S23. DVD3 is a CD2, which name is S23. It should return true. I think I would have to incorporate equalname (the method I used to compare two CDs in the CD class) somehow. What should I do?

import tester.Tester;

interface IBook{

    //return name 

    public boolean samename(IBook that);   
}
 class CD{
    String name;
    String color;
    CD(String name, String color){
      this.name=name;
      this.color=name;

    }  
       public String returnname(){
        return this.name;
    }

    public boolean equalname (CD that){
        return this.name == that.name;

    }
}

class mtlob implements IBook{

    public String returnname(){
        return "";
    }
    public boolean samename(IBook that){
        return false;
    }
}

class DVD implements IBook{
   CD first;
   IBook rest;

   DVD(CD first, IBook rest){
        this.first=first;
       this.rest=rest;

   }

   public boolean samename(IBook that){
       return this.first.equals(that); //this.rest.samename(that);

   }


}



class ExamplesX{

    CD CD1 = new CD ("S23", "blue");
    CD CD2 = new CD ("S23", "red");
    CD CD3 = new CD ("cs2, ", "black");
    CD CD4 = new CD ("HFF", "black");
    mtlob empty = new mtlob ();
    IBook DVD1 = new DVD (this.CD1, empty);
    IBook DVD2 = new DVD (this.CD3, this.DVD1);
    IBook DVD3 = new DVD (this.CD2, this.DVD1);

     boolean test(Tester t){
        return
        t.checkExpect(this.CD1.equalname(CD2), true)&&
        t.checkExpect(this.DVD1.samename(DVD3), true);


        } }

Upvotes: 0

Views: 127

Answers (4)

BillThePlatypus
BillThePlatypus

Reputation: 392

When comparing strings, you need to use the .equals method. == will only determine if the two variable point to the exact same string (the smae pointer), not two strings with the same text, for example:

string a="hello";
string b=a;
string c=getUserInput();//User inputs the string "hello"
System.out.println(a==b);
System.out.println(a==c);
System.out.println(a.equals(c));

will output

true
false
true

Upvotes: 1

Akhilesh Dhar Dubey
Akhilesh Dhar Dubey

Reputation: 2148

use equals method like this:

if((CD1.name).equals(CD2.name)){
    //........true
}

Upvotes: 1

Joe
Joe

Reputation: 1219

Just use == for primitive types.

Upvotes: 1

Ram Krishna Pandey
Ram Krishna Pandey

Reputation: 97

use a method equals instead of using ==

string1.equals(string2)

Upvotes: 3

Related Questions