+ 2
How can get the key of value in arraylist?
I have a teacher class Teacher has name and code. Arraylist<Teacher> teachers; Teacher t = new Teacher(); t.add(âteacher1â, 100); teachers.add(t); String name =teachers.get(teachers.IndexOf(100)).getName(); //this do not return name of teacher. Why??
6 Réponses
+ 1
think we have more than one teacher inside arraylist, and want get the name of a teacher with code, mean we have code and we need name, how can get that??
teachers[ârashbanâ 100, âhamidâ 101]
we have 100, how can get rashban without for?
+ 5
import java.util.ArrayList;
class Test
{
	public static void main(String args[])
	{
		Teacher t1 = new Teacher("Rishabh", 100);
		Teacher t2 = new Teacher("Hamid",101);
		ArrayList<Teacher> teacher = new ArrayList<Teacher>();
		teacher.add(t1);
		teacher.add(t2);
		System.out.println(t1.getNameByCode(100));
		System.out.println(t2.getNameByCode(101));
		
	}
}
public class Teacher {
	private String name;
	private int code;
	
	public String getName()
	{
		return this.name;
	}
	public int getCode()
	{
		return this.code;
	}
	public Teacher(String name, int code)
	{
	this.name= name;
	this.code=code;
	}
	public String getNameByCode(int code)
	{
		return this.name;
	}
}
+ 3
Where is your Teacher class??
+ 3
public class Teacher {
	private String name;
	private int code;
	
	public String getName()
	{
		return this.name;
	}
	public int getCode()
	{
		return this.code;
	}
	public Teacher(String name, int code)
	{
	this.name= name;
	this.code=code;
	}
}
class Test
{
	public static void main(String args[])
	{
		Teacher t1 = new Teacher("Rishabh", 100);
		ArrayList<Teacher> teacher = new ArrayList<Teacher>();
		teacher.add(t1);
		System.out.println(t1.getName());
		System.out.println(t1.getCode());
		
	}
}
// You can do this. Thanks for posting this question :-)
+ 1
public class Teacher{
    private String name;
    int code;
    
    public Teacher(){
        
    }
    
    //with getter and setter for name and code.
}
0
think we have more than one teacher in arraylist, how can get the name of a teacher when we have its code?



