How to get values from ArrayList - java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class clsWarehouse {
private static int iChoice;
private int iItemID;
private String strItemName;
private String strItemDescription;
private int iItemPrice;
private String strSize;
private String strSex;
public clsWarehouse (int id, String name, String description, int price, String size, String sex){
iItemID = id;
strItemName = name;
strItemDescription = description;
iItemPrice = price;
strSize = size;
strSex = sex;
}
public ArrayList <clsWarehouse> AllItems;
public clsWarehouse(){
AllItems = new ArrayList <clsWarehouse>();
AllItems.add(new clsWarehouse(3, "T-Shirt", "Male T-Shirt", 30, "15", "Male"));
System.out.println(AllItems);
}
public static void main(String[] args){
clsWarehouse c = new clsWarehouse();
}
}
}
Hello,
I want to get the values stored in the ArrayList AllItems but all i get is the memory location [clsWarehouse#a83b8a]. Can someone help me with this.
Thanks!

You need to override the toString() in your clsWarehouse class. The System.out.println internally calls the toString() of the object in the list. Since you do not have the toString() method overridden in your class, you get the below as your output.
getClass().getName() + '#' + Integer.toHexString(hashCode())
The above is the toString() implementation of the Object class.
Update:-
In your clsWarehouse class, add the below method.
public String toString(){
return "clsWarehouse"; //Modify this to return whatever you want to display in your sysout.
}

You need to iterate through the array list to get the values . Also need to convert this guy to string format using toString(). Then,
for (int i=0;i<AllItems .length();i++){
//Then get the values one by one
}
Hope this helps you .

Add this method in clsWarehouse class
public String toString(){
return "iItemID: " + iItemID +" strItemName: "+ strItemName + " strItemDescription: "+ strItemDescription +" iItemPrice "+ iItemPrice: + " strSize: " + strSize + " strSex: "+strSex;
}
Change this
System.out.println(AllItems);
to
for(clsWarehouse item : AllItems){
System.out.println(item.toString());
}

Related

How to print every element in array in loop if with different types of element?

I have this phone class:
public class Phone {
private int id;
private String brand;
private String model;
private int cameraResolution;
public Phone(int id, String brand, String model, int cameraResolution) {
this.id=id;
this.brand=brand;
this.model=model;
this.cameraResolution= cameraResolution;
}
public void showDetails() {
System.out.println("id "+ this.id);
System.out.println("Marka to "+ this.brand);
System.out.println("Model to "+ this.model);
System.out.println("Rozdzielczosc aparatu to " + this.cameraResolution);
}
and this main class
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Phone galaxy= new Phone(1, "Samsung","Galaxy",12);
Phone lumia= new Phone(2, "Nokia","Lumia",13);
Phone pixel= new Phone(3, "Google","Pixel",14);
galaxy.showDetails();
//String[] phones = new String[3];
//phones[0]="galaxy";
//phones[1]="lumia";
//phones[2]="pixel";
Phone[] phones = new Phone[3];
phones[0]= galaxy;
phones[1]= lumia;
phones[2]= pixel;
// dont work System.out.println(Arrays.oString(phones));
}
}
I want to write a loop, that will call the phone.showDetails() method from the phone's array, but I can't find a way to do it. There's a problem with data type conversion or sth.
I want to achieve a loop, that will call:
galaxy.showDetails, then lumia.showDetails() and pixel.showDetails();
You can loop through every element and print its details.
for (Phone phone: phones){
phone.showDetails();
}
Your big issue is your phone class doesn't override toString(), so all youre going to see is memory address space. Do something like this:
#Override
public String toString() {
return "Phone [id=" + id + ", brand=" + brand + ", model=" + model + ", cameraResolution="
+ cameraResolution + "]";
}
As for looping through, there are lots of ways you can do this, but the easiest:
for (Phone phone : phones) {
System.out.println(phone);
}

the contents of arraylist are printed using println. I want a similar functionality for my created objects without using toString() function in java

In the image above, the contents of the arraylist is printed using println. I want a similar functionality for my created objects without using toString() function in java
please tell me how can i do that
To facilitate the answer, I added a CustomClazz with toString method and two fields(firstField, secondField) to be printed. The code uses both the toString method and Stream-> println of each object;
import java.util.ArrayList;
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
ArrayList<CustomClazz> list = new ArrayList<>();
list.add(new CustomClazz("custom1","class1"));
list.add(new CustomClazz("custom2","class2"));
list.add(new CustomClazz("custom3","class3"));
//Stream that accesses and concatenates each field of custom class.. notice the bad concatenation "+"
list.stream().map(customClass -> customClass.getFirstField()+ customClass.getSecondField()).forEach(System.out::println);
System.out.println();
System.out.println();
//Option that uses the toString method of customClazz.
System.out.println(Arrays.toString(list.toArray()));
}
}
class CustomClazz {
String firstField;
#Override
public String toString() {
return "CustomClazz{" +
"firstField='" + firstField + '\'' +
", secondField='" + secondField + '\'' +
'}';
}
String secondField;
public String getFirstField() {
return firstField;
}
public void setFirstField(String firstField) {
this.firstField = firstField;
}
public String getSecondField() {
return secondField;
}
public void setSecondField(String secondField) {
this.secondField = secondField;
}
public CustomClazz(String firstField, String secondField) {
super();
this.firstField = firstField;
this.secondField = secondField;
}
}

Printing elements of list of objects [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
//contacts class
package com.company;
public class Contacts {
private String name;
private String number;
public Contacts(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
//class Phone
package com.company;
import java.rmi.StubNotFoundException;
import java.util.ArrayList;
public class Phone {
private ArrayList<Contacts> contacts1 = new ArrayList<Contacts>();
public void addContact(String name, String numbers) {
Contacts contacts = new Contacts(name, numbers);
contacts1.add(contacts);
}
public void printContacts() {
for (int i = 0; i < contacts1.size(); i++) {
System.out.println(contacts1.); // >>> how to print elements (name and phone number)
}
}
}
Here I tried to print a list of contacts including name and phone number but could not handle how to iterate over a list of objects. How can I print name and phoneNumber using printContacts() method in Phone class?
Thanks
You would do:
System.out.println(contacts1.get(i));
but that would just give Contacts#somenumber, so you will need to add a toString() method to the Contacts class.
In the contacts class, add a function that looks like this:
#Override
public String toString() {
return name + ": " + number;
}
Override toString method in your class Contacts to return a string representation of your class object (for e.g. json string). System.out.println prints string returned by this method.
public class Contacts {
private String name;
private String number;
...
#Override
public String toString() {
return "{\"name\": \"" + name + "\", \"number\": \"" + number + "\"}";
}
}
P.S. If you are using one the java IDEs, check out the implementation of println method in file PrintStream.java in java source code. Java IDEs provides this feature of code navigation in your project by which you can actually navigate through source code of Java itself.

Trouble using HashMap containing Objects

Please pardon my bad English
I am trying to create a HashMap with a String as a key, and an Object as parameter, which I want to initialise each time the program runs so that its added to a new key in the HashMap.
The problem is, that not all values are returned, and namely the second, gives back a weird output.
package javaex1;
import java.util.*;
public class Javaex1 {
public static void main(String[] args) {
Person obj = new Person("Eminem", "Male");
HashMap<String, Person> MapPerson = new HashMap<String, Person>();
MapPerson.put("Eminem", obj);
System.out.println(MapPerson);
}
}
The object
package javaex1;
public class Person {
String Name;
String Gender;
public Person (String name, String Gend) {
this.Name = name;
this.Gender = Gend;
}
public String getName() {
return Name;
}
public String getGender() {
return Gender;
}
}
Any help or hint is greatly appreciated! Thank you in advance for your time!
The expected results should be "Eminem Male". Instead what I get is this:
{Eminem=javaex1.Person#2a139a55}
This happens because you are trying to print an Object, An Object when printed gives the default toString implementaion of Object class , which is shown below
// implementation of toString in Object class
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
This is what you can see in your current output .
You should ovverride toString method in Person class like this.
public String toString() {
return this.Name + " " + this.Gender;
}
So that it returns the name and gender
You should override toString method in Person class. Like that:
#Override
public String toString() {
return this.Name + " " + this.Gender;
}
You're printing the MapPerson object, not the Person one.
Your code should be:
Person person = MapPerson.get("Eminem");
System.out.println(person.getName() + " " + person.getGender());

HashMap Issuses

Edited the getTypeString method in the Flowers class now I just get the pointer to the object
I'm working on a project for one of my classes. I haven't worked with HashMap before and I need to use one. In this java class I'm trying to print out the full description that I have set. But it wont print the HashMap value from the key. I have tried to use some code from my book, but with no luck.
This is the class that is calling the class that has the HashMap:
public class Garden
{
private Gardener gardener;
private Tools tools;
private Flowers flowers;
/**
* Constructor for objects of class Garden
*/
public Garden()
{
gardener = new Gardener();
tools = new Tools();
Flowers rose;
rose = new Flowers("a beautiful red flower");
rose.setFlower("red", rose);
System.out.println(rose.fullDescription());
}
}
Edited the getTypeString method
This is the class that is using the HashMap:
import java.util.Set;
import java.util.HashMap;
public class Flowers
{
private String fDescription;
private HashMap<String, Flowers> flowers;
/**
* Constructor for objects of class Flowers
*/
public Flowers(String fDescription)
{
this.fDescription = fDescription;
flowers = new HashMap<String, Flowers>();
}
public void setFlower(String color, Flowers type)
{
flowers.put(color, type);
}
public String flowerDescription()
{
return fDescription;
}
public String fullDescription()
{
return "The "+ getTypeString() + " is " + fDescription;
}
private String getTypeString()
{
String des = "";
Collection<Flowers> vals = flowers.values();
for(Flowers f : vals){
des += f;
}
return des;
}
}
The problem, I think, is in the getTypeString() function. Can anyone point me in the right direction?
Edit
I removed the getTypeString method and edited the fullDescription method:
public String fullDescription()
{
return "The "+ type + " is " + fDescription;
}
now I'm trying to get the 'HashMap' to print the objects like so:
"Flower [type= type, description= Description "]"
using thes methods:
public static void printHashMap()
{
System.out.println("hashmap: " + flowers);
}
#Override
public String toString()
{
return "Flower [type=" + type + ", description=" + fDescription ]";
}
From your post, what I have understood is that you want to print the description of flowers. So I think you can try something like:
private String getTypeString(){
String des = "";
Collection<String> vals = flowers.values();
for(String f : vals){
des = des + f.flowerDescription();
}
return des;
}
Override the toString method in your class
Declare a toString method with the following modifiers and return type:
#Override
public String toString() {
return this.fDescription;
}
Implement the method so that it returns a string.

Categories

Resources