Get value of object in generic array instead of classpath [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
I have an generic array class that stores other objects. When I try to get the object values from the generic array it prints the insert objects classpath. How can I access the value?
public class Shop implements Initializable {
#FXML private TextField name;
#FXML private TextField quantity;
#FXML private TextArea list;
MyArrayList<Item> array = new MyArrayList<>();
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#FXML
private void addItem() {
int q = Integer.parseInt(quantity.getText());
String n = name.getText();
Item item = new Item(n,q);
MyArrayList.getInstance().add(item);
System.out.println(MyArrayList.getInstance().getItem(0));
//Outputs sample.Item#1674184b instead of the value Banana.
}

So your are putting an Integer and a String into the Item?
MyArrayList.getInstance().getItem(0).getName() or
MyArrayList.getInstance().getItem(0).getQuantity()
should print out the values u put it.
If you dont have the get methods create them, or if the fields are public you could access them directly.
U might want to overwrite the toString() method if u want to get all the values from the class listed like.
#Overwrite
public String toString(){
return name + "," + quantity;
}
And call
System.out.println(MyArrayList.getInstance().getItem(0).toString());

Related

How to print content of an object [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
How to override toString() properly in Java?
(15 answers)
Closed 2 years ago.
I'm trying to fetch a list from MySQL on android but I'm getting
[com.trycatchsoft.app.Models.KatPojo#7553fa]
as output instead of list.
Here is my pojo file:
package com.trycatchsoft.app.Models;
public class KatPojo {
private Boolean tf;
private String veri;
private String verid;
public Boolean getTf() {
return tf;
}
public void setTf(Boolean tf) {
this.tf = tf;
}
public String getVeri() {
return veri;
}
public void setVeri(String veri) {
this.veri = veri;
}
public String getVerid() {
return verid;
}
public void setVerid(String verid) {
this.verid = verid;
}
}
By default, printing an Object results in a class name and hash code. One can change this result by overriding the toString() method inherited by all children of Object.
When you're working with the Object type, you need to override the toString() method and call this method if you want to get the string representation of this object.
you can also use https://github.com/google/gson
If you are debugging I find it easy to just print the json instead of writing toString. You can pass your object or an array of objects.
Gson GSON = new GsonBuilder().setPrettyPrinting().create();
System.out.println(GSON.toJson(<PASS YOUR OBJECT REFERENCE HERE>));

How can i add to a Linked List in Java [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
am writing a program on linked list in Java but am confused on why the right values are not been added. I want to add the student name and StudentNo together as they for one student. Below is the code.
package linked;
public class PlsWork {
private String name;
private int studentNo;
public PlsWork(String name, int studentNo){
this.name=name;
this.studentNo=studentNo;
}
public String getname(){
return name;
}
public int getstudentNo(){
return studentNo;
}
}
package linked;
import java.util.LinkedList;
public class Linked {
public static void main(String[] args) {
LinkedList myLinkedList = new LinkedList();
myLinkedList.addFirst("A");
System.out.println(myLinkedList);
PlsWork ok = new PlsWork("obinna",3);
myLinkedList.add(ok);
System.out.println(myLinkedList);
}
}
when i run the code i get the answer below
[A, linked.PlsWork#6d06d69c]
Instead of [A,obinna 3]
linked.PlsWork#6d06d69c is the reference to your object. That is what toString shows by default. You may want to override toString on your PlsWork-class for example as follows:
class PlsWork {
...
#Override
public String toString() {
return name + ' ' + studentNo;
}
}

Printing out an ArrayList consisting of Arrays [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
For an assignment in my programming class I need to create a program that can store countries. Every country has a name, a population & an area. (KM^2)
import java.util.ArrayList;
import java.util.Arrays;
//Main Class//**
public class P820_Country_Main {
public void run() {
Country Nederland = new Country("Netherlands", 17000000, 41543);
Country Duitsland = new Country("Gernany", 80620000, 357376);
ArrayList<Country> countries = new ArrayList<Country>();
countries.add(Nederland);
countries.add(Duitsland);
System.out.println(Arrays.toString(countries));
}
public static void main(String[] args) {
new P820_Country_Main().run();
}
}
The country class:
public class Country
{
private String countryName;
private int countryPopulation;
private int countryArea;
private double populationDensity;
public Country(String countryName, Integer countryPopulation, Integer countryArea)
{
this.countryName = countryName;
this.countryPopulation = countryPopulation;
this.countryArea = countryArea;
}
}
The issue I'm currently facing is that I can't seem to print out my ArrayList. Every spot of the ArrayList is basically an Array of its own. (Containing a String for the country's name, an int for the population & an int for the area. (Ignore the density variable, that is for later in the assignment)
The way I printed out ArrayList up until this point was as follows
System.out.println(countries);
When I do this with my current ArrayList it will print out the addresses instead of what's inside of the Array.
How do I get it to print out the ArrayList?
Try to declare toString() method in Country class:
public class Country
{
...
public String toString(){
return "Name: "+countryName+", population: "+ countryPopulation + ", area: "+countryArea;
}
...
}

Creating an ArrayList of objects causes each element to be the same [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
I'm new to Java and Android. Part of an app I'm writing reads item data from a file and populates an ArrayList of items prior to using it to populate a ListView.
From main.java:-
public class MainActivity extends AppCompatActivity {
public static ArrayList<Item> items;
.
.
.
private void ReadItemsFile() throws IOException {
File itemsFile = new File(itemsFilenameString);
items = new ArrayList<Item>();
try (BufferedReader itemsBufferedReader = new BufferedReader(new FileReader(itemsFile))) {
for (String line; (line = itemsBufferedReader.readLine()) != null; ) {
String[] lineStrings = line.split("\t|\n", 2);
int itemNo = Integer.parseInt(lineStrings[0]);
items.add(new Item(itemNo, lineStrings[1]));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
From Items.java:-
public class Item {
private static int idInt;
private static String description;
private static Image image;
public Item(int idInt, String description) {
this.idInt = idInt;
this.description = description;
this.image = image;
}
}
but when I run this I find that the ArrayList (and ListView) is full of items that all are the same as the last one read from the file. I've tried debugging this and found that all the items in the ArrayList are changed to the last one added after the line:-
items.add(new Item(itemNo, lineStrings[1]));
Please can someone explain why this is and how to fix it?
I've previously checked Creating an ArrayList of Objects on this site and found my method of ArrayList population to be the same as was suggested.
In your Item class , can see the variables to be of type static which could be a possible reason. Try removing static keyword as in this scenario, these variables/properties values are dependent on the object instead of being common for all objects
public class Item {
private int idInt;
private String description;
private Image image;
public Item(int idInt, String description,Image image) {
this.idInt = idInt;
this.description = description;
this.image = image;
}
Hope this solves your problem..
I've run into this issue before. I was unable to find a solution at the time, so I ended up taking a different approach, which was to use an SQLite database to store information about my items in local storage. I am not sure this helps you, but it is a viable alternative to storing data on regular files.
Using static for the fields in your Item class causes them to belong to the class, not to the instance of the class.
Each time you create a new Item, you're resetting the class fields to the new values. Your Item objects don't have any instance-specific data delared.

Printing address instead of array elements? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
So in my code, I made a class named Pet, that would have both a default constructor and a non-default constructor that passes in String name, and int age of the pet.
public class Pet
{
// instance variables
private int age;
private String name;
/**
* Constructor for objects of class Pet
*/
public Pet()
{
// initialise instance variables
age = 0;
name = "somePet";
}
public Pet(int age, String name)
{
this.age = age;
this.name = name;
}
}
Then I created a class named petArray that would add to the array and print out the array...
public class PetArray
{
// instance variables
private Pet [] petArray;
/**
* Constructor for objects of class PetArray
*/
public PetArray()
{
// initialise instance variables
petArray = new Pet[5];
}
public void addPets()
{
// put your code here
Pet myPet = new Pet(4, "Spots");
petArray[0] = (myPet);
petArray[1] = new Pet(2, "Lucky");
petArray[2] = new Pet(7, "Joe");
}
public void printPets()
{
for (int i = 0; i < petArray.length; i++)
{
System.out.println(petArray[i]);
}
}
}
But then, I get this in the terminal window when trying to print it out...
Pet#13255e3c
Pet#171ac880
Pet#52185407
null
null
You forgot to override toString() method inherited from Object.
In this case you can use something like this:
#Override
public String toString() {
return (name + age);
}
Java compiler just does not know how to print it, you have to inform it :)
In your addPets() method you are only adding 3 objects to your petArray while there are 2 more spaces you need to fill as you declared that array to be a length of 5.
You could change the length of your array down to 3 or you could add 2 more objects, that should fix your problem.
And as stated above, adding the toString method will get rid of the addressing issues.
class Pet {
...
#Override
public String toString(){
// the string passed from here will be shown in console
}
}
Your output is fine according to your code. You have to override toString() method to print as per your requirement. Add this may be it will help.
#override
public string toString(){
return "your required string"; // i.e : name or name+age
}

Categories