Iterator is adding the wrong address - java

In my program I've added an ArrayList of another class type but when I iterate the list I get a wrong address.
For example my code is
ArrayList<Student> stdntList = new ArrayList<Student>();
stdntList.add(new Student("Candace","633501"));
stdntList.add(new Student("Curtis ","634572"));
stdntList.add(new Student("Amber","623343"));
System.out.println(stdntList);
Iterator itr = stdntList.iterator();
while(itr.hasNext())
{
System.out.println("Student: " + itr.next());
}
and my output is
Student Name: Candace Student ID633501
Student Name: Curtis Student ID634572
Student Name: Amber Student ID623343
[Student#659e0bfd, Student#2a139a55, Student#15db9742]
Student: Student#659e0bfd
Student: Student#2a139a55
Student: Student#15db9742

In order to take the address, you should maybe print something like this System.out.println("Student: " + itr.next().getAddress());
As it is now, it prints everything it is on .toString() method. You have to override this method in order to print the address by calling only the reference to the class.

Related

how to override this to get structured manner

i am creating student management simple java project using Maps collection where id is my key and the name,marks and mobile no. are values for the map. So how to print it in structured manner.
HashMap<Integer, LinkedHashSet<StudentCinstructor>> st = new HashMap<>();
LinkedHashSet<StudentCinstructor> st2 = new LinkedHashSet<>();
Scanner sc = new Scanner(System.in);
public void add() {
System.out.println("enter the name of the student");
String name = sc.nextLine();
System.out.println("enter the marks of the student");
double marks = sc.nextDouble();
System.out.println("enter the mobile number of the student");
long mobile_no = sc.nextLong();
st2.add(new StudentCinstructor(name, marks, mobile_no));
System.out.println("enter the unique id of the student");
int id = sc.nextInt();
st.put(id, st2);
with the custom class when i am trying to print it in main method its giving me an address with hashcode.
"HashmapDemo.MethodsForManagement#3d4eac69"
Two remarks :
1- When you try to print the object StudentCinstructor, if there is no dedicated toString() method, you will not get a well structured output. Therefore, what you need to do is write a toString() method for your class and then you can print to console.
Example :
public static String toString() {
return "Customize here + Put this method inside your class";
}
2- I don't see why you are using LinkedHashSet to store the StudentCinstructor objects and then storing this HashSet inside a map rather than creating the StudentCinstructor object and storing it in the Map directly if all students have a unique id.
Such as :
HashMap<Integer, StudentCinstructor> st = new HashMap<>();
Looking at your printed output "HashmapDemo.MethodsForManagement#3d4eac69", it seems you are printing an object of class HashmapDemo.MethodsForManagement. If you want to print an object of StudentCinstructor, you need to pass that object to the print method like System.out.println(student);.
And you need to override the toString() method in StudentCinstructor class. (i.e. put below code in StudentCinstructor class.)
(name, marks and mobile_no in below code are the fields in StudentCinstructor class.)
#Override
public String toString()
{
return "Name=" + name + ", Marks=" + marks + ", Mobile number=" + mobile_no;
}

How to group content and add it to ArrayList as one object?

I have a list of Students with the following details say Name, Id, Subject so now I want to use a data structure in which one object stores Name, Id and Subject
For example
Name: Snow
Id=1
Subject=CS and
Name: John
Id=2
Subject =IT
How do I do that?
Create the List of that Student class and add the objects in list . but you have to initialize your class properties either by constructor or setter methods, below example is only to show you how objects can store in List.
List <Student> studentList = new ArrayList<Student>();
Student s1= new Student();
studentList.add(s1);
Create a object for HashMap class and by using put() method of it pass all the id and subject name as it takes the combination of id and name then convert it to a object of Set class and lastly by using the addAll() method of ArrayList pass set class object to the addAll() method its done, we have not passed the hashmap object because hashmap class does contains allAll() method,below are the codes hope it helps you
import java.util.*;
public class GroupA{
public static void main(String...s){
ArrayList al=new ArrayList();
HashMap<Integer,String>hs=new HashMap<>();
hs.put(100,"aaa");
hs.put(101,"bbb");
hs.put(102,"ccc");
Set sp=hs.entrySet();
al.addAll(sp);
System.out.println(al);
}
}

Use a Object by String?

Is it possible to use a Object if i only got the String? I have an Object 'John' from the Class 'Student'. In the Class 'Student' is a ArrayList 'friends'. I want to access the Object 'John' by using a String (the name of the object). (Line 2 in the example)
public void addFriend(Student student, String friend) throws IOException{
student.friends.add(friend);
System.out.println("Friend: " + friend + " added to List of " + student);
}
I hope you understand what i mean (i am sorry for my terrible english :/ )
You can use map for this problem.
Map<String, Student> friends = new HashMap<String, Student>();
friends.put("John", objectOfJohn);
Student target = friends.get("John");
If I understand correctly, you want to print out name of a student using the variable student. If this is the case, you may want to override the toString() method inside Student class which returns name of that student. For example:
public class Student {
private String firstName;
private String lastName;
// ... Other methods
// here is the toString
#Override
public String toString() {
return firstName + " " + lastName;
}
}
Then you can do something like this to print out the student name:
System.out.println("Friend: " + friend + " added to List of " + student.toString());
You have a Student Class and you have created in some point some objects of this class.
Student john = new Student();
Student mike= new Student();
Student mary = new Student();
and you have all these objects stored in an Arraylist allStudents
ArrayList<Student > allStudents= new ArrayList<>();
allStudents.add(john);
allStudents.add(mike);
allStudents.add(mary);
So, if you want to find john from this list you may do:
Option A
If the name for your case is unique and exists also as an attribute in your object, you can iterate the Arraylist and find it:
Student getStudentByName = new Student();
for(Student student : allStudents){
if(student.getName().equals("john")){ //If name is unique
getStudentByName = student;
}
}
Option B
Add all objects in HashMap
Map<String, Student> allStudents= new HashMap<>();
allStudents.put("john", john);
allStudents.put("mike", mike);
allStudents.put("mary", mary);
And then get your desired object by:
Student target = friends.get("john");
Be mind that if you add again :
allStudents.put("john", newStudentObject);
the HashMap will keep the last entry.

Inputting strings into arrayLists?

Suppose that I have a code empList and it is an ArrayList. I have 3 Strings, name, boss, and dob holding the data for some employee. I want to write code that creates an Employee from my Strings and then adds it to the empList. I can use the add method of ArrayList to add my employee after I have constructed it, but I'm not too sure how.
This is my Employee class I have written so far:
ArrayList<String> empList = new ArrayList<String>();
class Employee{
Employee(String dob, String name, String boss) //(constructor)
//dob should be mm/dd/yyyy, and boss of length 0 indicates no boss.
int getAge()
String getName()
String getBoss() //returns length 0 string if none
String getDob()
You should change the List declaration to List<Emloyee>:
List<Emloyee> empList = new ArrayList<Emloyee>();
(read more about generics in Java: http://docs.oracle.com/javase/tutorial/java/generics/)
Then you can create a new Employee instance and add it to the list:
Employee employee = new Employee("dob", "John Smith", "His Boss");
empList.add(employee);
By the way: consider changing the type of boss from String to Employee (depending on you use case/meaning).
You might be able to do it in your constructor using
empList.add(this);
However, you'd have to change the type of your ArrayList to Employee, or if you wanted to keep it as a String, then you'd have to create a String in your constructor, and do
String str = "Your string here";
empList.add(str);
I'm also pretty sure that you can't have your ArrayList outside of your class. Java doesn't let you have things outside of classes.
You can add strings to the ArrayList by it's add() method.
You already have the getXXX() methods in your employee class, so you can simply do something along the lines of
String str = "Name: " + emp.getName() + ", Boss: " + emp.getBoss() + ", DoB: " + emp.getDoB();
empList.add(str);
What you probably want is an ArrayList of Employees (ArrayList<Employee>), which would be added in a similar manner, without adding everything to a string.

Iterate ArrayList and get match items Id

I have an ArrayList which contains data like profId, firstname, lastname, age.
Now I have a lastname and firstname, which gets from user form side. Now I want to compare them with an ArrayList. If both match, I want to retrieve "respective profId".
e.g arraylist contains data like
profId lastname fistname age
1 roy sam 25
2 ryob arnav 30
Now user will type lastname and firstname as roy and sam respectively. I will get this data by their getter methods.
Now, how should I compare these 2 names with the ArrayList so that I will get the perfect profid of him as:
'1'.
I am trying to compare by this way.
// existPatList is arraylist patfamily is object of Family from where I will get users value
for(Family p : existPatList) {
System.out.println("Last name" +p.getLastName());
System.out.println("First name"+p.getFirstName());
if(p.getLastName().equalsIgnoreCase(patFamily.getLastName())) {
System.out.println("got it");
}
}
How can I solve this problem?
Use a && in your if condition with both firstName and lastName.
for(Family p : existPatList) {
System.out.println("Last name" +p.getLastName());
System.out.println("First name"+p.getFirstName());
if(p.getFirstName().equalsIgnoreCase(patFamily.getFirstName()) && p.getLastName().equalsIgnoreCase(patFamily.getLastName())) {
System.out.println("got it");
}
}
To get profId replace your line:
System.out.println("got it");
with
System.out.println(p.getProfId); //or do whatever you wanna do with profId
I consider here the you getters also has a get method for profId, that is getProfId()

Categories