Array prints memory address despite Override [duplicate] - java

This question already has answers here:
I am getting the memory address from an arraylist, need info
(2 answers)
Closed 8 years ago.
Now, I want it to only print what it says, without the memory address as well. How would I achieve that?
public Telefonnummer[] getTelenummer() {
Telefonnummer[] tnummer = new Telefonnummer[nummerarray.size()];
nummerarray.toArray(tnummer);
System.out.println(Arrays.toString(tnummer) );
return tnummer;
}
Is the constructor and:
private static void kundSök() {
System.out.println("...? ");
String namn = keyboard.nextLine();
if (kunderna.containsKey(namn)) {
for (String k : kunderna.keySet()) {
Kund kund = kunderna.get(k);
System.out.println(kund);
System.out.println(kund.getTelenummer());
After i have added a person to the ArrayList etc it gives me an output of:
Sam wasdfgn
[123456: efdg]
[LTelefonnummer;#28d93b30
The last part, memory address bit, is the part I want to get rid of.
Yet again, how do i achieve that?
Edit: I tried to Override, but it did not do anything at all. Could there be another problem?

The default behaviour for toString is to print the type name (as L followed by the type name), followed by # and the hexString of the hashCode (which by default is the memory address for the object).
To change this, override the toString method for your Telefonnummer class.
public class Telefonnummer {
private String nummer;
...
#Override public String toString() {
return "Dial " + nummer + " for a good time";
}
}

Guava library has Joiner which can be used for that. See https://code.google.com/p/guava-libraries/wiki/StringsExplained
String str = Joiner.on(",").join(list);
You also have to have working toString function on class for elements of the list

Related

Best way to find if String is not in the list of ENUMs [duplicate]

This question already has answers here:
Java: Check if enum contains a given string?
(32 answers)
Closed 3 years ago.
I need to find if given String is not in the list of ENUMs.
These Strings come back with spaces, i.e.: "CHILD CARE", "CREDIT CARDS", etc...
Any other ExpenseType should be mapped to OTHER, except HOA. HOA should be completely ignored.
My ENUMs are as follows:
public enum ExpenseType {
AUTOLOAN("AUTO LOAN"),
ALIMONY("ALIMONY"),
CHILDCARE("CHILD CARE"),
CREDITCARDS("CREDIT CARDS"),
INSTALLMENTLOANS("INSTALLMENT LOANS"),
FOOD("FOOD"),
UTILITIES("UTILITIES"),
TRANSPORTATION("TRANSPORTATION"),
OTHER("OTHER");
private String expenseType;
ExpenseType(String expenseType) {
this.expenseType = expenseType;
}
#Override public String toString() {
return this.expenseType;
}
}
The way I am doing this now is as follows:
String expenseDescription = expense.getExpenseDesc().replaceAll(" ", "");
if(EnumUtils.isValidEnum(ExpenseType.class, expenseDescription)) {
monthlyExpenses.setType(ExpenseType.valueOf(expenseDescription).toString());
}
else if(!expenseDescription.equals("HOA")) {
monthlyExpenses.setType(ExpenseType.OTHER.toString());
}
Does anyone know a better way to do this?
Why not use getEnum to get Enum if applicable (check for null or use Optional
if needed)
ExpenseType monthlyExpenses = EnumUtils.getEnum(ExpenseType.class, expenseDescription);
Gets the enum for the class, returning null if not found.
This method differs from Enum.valueOf(java.lang.Class, java.lang.String) in that it does not throw an exception for an invalid enum name.
Also prefer adding to enum a code (String) as a reference, which won't contains spaces and special characters, e.g.
//...
CHILDCARE("CHILD_CARE","CHILD CARE"),
//...
private String expenseType;
private String expenseTypeCode;
ExpenseType(String expenseType, String expenseTypeCode) {
this.expenseType = expenseType;
this.expenseTypeCode = expenseTypeCode;
}
Here is another alternative.
Map<String, String> codes = Arrays.stream(ExpenseType.values()).collect(
Collectors.toMap(ExpenseType::toString, ExpenseType::name));
codes.put("HOA","TBD");
String[] submittedCodes = { "CREDIT CARDS", "FOOD", "UTILITIES", "UNKNOWN"
};
for (String c : submittedCodes) {
String expenseType = codes.getOrDefault(c,"OTHER");
System.out.println(expenseType);
}
First, I didn't see a reason to remove the spaces from the submitted code unless you are concerned about addition of extra spaces creeping in. In that case you should probably also remove tabs.
Since you are already using the enum value to compare to the name, I figured I would just ignore the name as they are effectively the same.
The map is used only to allow a null to be returned in case of a missing key.
The enum was only used to conveniently populate the map.
I did not know exactly how to handle HOA. But all of this is just another alternative for you to possibly investigate as you can rearrange the keys and values, etc to suit your requirements.

My arraylist is displaying object address not object contents [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
arraylist displays object address not actual object , program usesinheritance where salesEmployee is the super class and salesAgent and salesPerson are the subclasses.
import java.util.Scanner;
import java.util.ArrayList;
public class tester {
public static void main(String[]args ) {
ArrayList <salesEmployee> listemps= new ArrayList <salesEmployee>();
Scanner user_input= new Scanner(System.in);
salesPerson emp1 = new salesPerson();
emp1.setName("Frank Long");
emp1.setppsNumber(65783);
System.out.println("Enter total value of sales earned by Frank Long");
double valeSale;
valeSale=user_input.nextDouble();
emp1.setvalSale(valeSale);
emp1.getCommission();
listemps.add(emp1);
for ( int j=0; j<listemps.size(); j++ )
System.out.println("element " + j + ": " + listemps.get(j) );
}
}
This is my salesPerson class
public class salesPerson extends salesEmployee{
public salesPerson() {
}
public salesPerson(String name, int ppsNumber, double valSale, double commission) {
super(name, ppsNumber,valSale,commission);
}
public void getCommission() {
commission=valSale*0.15;
}
public String toString2() {
return toString1()+"value of sales"+getvalSale()+"commission:"+commission;
}
}
I'll make it more elegant later for now I am just trying to get it to work
Updated: Based on the comments to my answer, there is a different issue at play. Here's what was added in the comments:
Enter total value of sales earned by Frank Long 22.00
Exception in thread "main" java.lang.StackOverflowError at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) – lucylio 5 mins ago
Is what comes up – lucylio 5 mins
In order for something reasonable to be displayed, you need to implement toString method in your class. You do have toString1 and toString2, but seemingly, no toString. (You haven't posted the code for salesEmployee class - but most likely it also doesn't have toString implementation).
In absence of toString, default Object.toString is called, which displays the address of the object.
Implement toString - and you'll see your results.
UPDATE: As the error you indicated doesn't correspond to the code, I'll go on a whim and suggest that, probably your toString2 method is actually toString and your toString1 method is actually a toString defined in your parent class, i.e. salesEmployee.java. In this case, instead of calling toString() from inside your toString method, use super.toString() instead:
public class salesPerson extends salesEmployee {
...
public String toString2() {
return super.toString()+"value of sales"+getvalSale()+"commission:"+commission;
}
}

output from the array list looks like address instead of data

a simple android program which accept a user id and user name, and store them inside an arrayList using a subclass called Student. There are 2 buttons, one of them record the information and the other one display them. The top button seem to work fine, but for the other one it display something that looks like the address instead of the actual data, what's the problem? Thanks
Override Object.toString() in your Student class.
//Sample code
public String toString() {
return "id of the student:" + this.id + ",, "
+ "name of the student:" + this.name ;
}
For more info, see this answer
use this code for you funclist method
private void funclist(){
StringBuilder output = new StringBuilder();
for(int i=0;i<studentList.seize();i++){
output.append(studentList.get(i) + "\n");
}
}
this will convert your object to string or you can add
studentList.get(i).toString()
instead of your code.

How to check if a String value already exists in a Array list?

I have two classes in BlueJ, SuperHero and SuperWeapon. I need to create a method that adds super weapons in the Arraylist. The method is supposed to be called with a parameter of the type SuperWeapon.
This means that the method assumes that a SuperWeapon object exists. The method is therefor not supposed instantiate a new SuperWeaponobject.
And only weapons with unique names may be added to the list, therefor a control of the new SuperWeaponobject is needed.
The code below is what i currently have, from what I understand, the code right now does not check if a superweapons name is unique when made. Sorry if the code is a little bit weird, i translated it to english from swedish but I hope someone understands what I am in need of.
Code:
import java.util.ArrayList;
public class SuperHero
{
private ArrayList<SuperWeapon> superWeaponList;
private String superHeroName;
public SuperHero()
{
superHeroName = "Superman";
superWeaponList = new ArrayList<SuperWeapon>();
}
public void addSuperWeapon(SuperWeapon superWeapon)
{
if(superWeaponList.contains(superWeapon))
{
System.out.println("The Superhero already has a superweapon with the name: " + superWeapon.getName() + ".");
}
else
{
superWeaponList.add(superWeapon);
System.out.println("A new superweapon has been registred for the superhero");
}
}
}
There are two options to solve your problem either change to a HashMap<String, ArrayList<SuperWeapons>> which maps the superhero's name to his weapons or else override the equals method in the superhero's class such that two superhero's are equal if their names are the same rather than the same object i.e., memory location

Print Array of Objects in BlueJ [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, I was asked to work on calling a class and creating an array objects, which i did here;
public void DVDArrayObjects() {
//creates variables
int i;
DVDClass[] dvdArray = new DVDClass[5];
//reference to DVDClass
for (i = 0; i < 2; i ++) {
//create new instance of calling the class
dvdArray[i] = new DVDClass();
//create new instance of getting the info
dvdArray[i].getDVDInfo();
//display
//System.out.println(dvdArray[i]);
}
}
Creating the array of objects works fine, but displaying doesn't. it shows the memory allocation when i run it. I'm really stuck as to how to get it to display.
** EDIT **
When i use System.out.println(dvdArray[i].getDVDInfo()); the error void types not allowed in here shows up
** END OF EDIT **
Any help at all would be greatly appreciated.
Print the DVD info (assuming that it returns a string).
System.out.println(dvdArray[i].getDVDInfo());
If it doesn't return a string, you need to override the toString() method on the class DVDInfo like this.
#Override
public String toString()
{
return "Film Name\t: " + filmName +
"\nFilm Director\t: " + filmDirector +
"\nRun Time\t: " + runTime +
"\nLead Actor\t: " + leadActor;
}
Hope this helps.
You need to override the toString() method.
public class DVDCLass {
#Override
public String toString(){
return // whatever you want the output to be
}
}
Override toString() method in your DVDClass class
do like below
class DVDClass{
public String toString(){
return // whatever you want the output to be
}
}

Categories