Java toString() not printing the correct variable [duplicate] - java

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 7 years ago.
I have a class like this in Java:
public class Wrapper {
public static List<Type> list;
#Override
public String toString() {
return "List: " + this.list;
}
public static void main(String[] args) {
Wrapper w = new Wrapper();
System.out.println(w);
}
}
and a class like this:
public class Type {
private static String name;
public Type(String n) {
this.name = n;
}
#Override
public String toString() {
return this.name;
}
}
Instead of getting the name of each item, I get the name of the last item for each item in the array. Any suggestions?

in your Type class you are marking your name as static so when printing type.toString() you always have only one value.
And if you want to print all member of your list, use:
for(Type t : list){
System.out.print(t.toString());
}

#Override
public String toString() {
String s = "";
for(Type t : list) {
s += t;
}
return s;
}

Related

java.lang.Object cannot be converted to the class i created [duplicate]

This question already has answers here:
What are Generics in Java? [closed]
(3 answers)
Closed 3 years ago.
im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing"
error when running the following code
public class Test1
{
public static void main(String args[])
{
Thing whipersnaper = new Thing(30, "whipersnaper");
List storage = new List();
storage.insert(whipersnaper);
Thing x = storage.getItem(0);
x.doubleWeight();
System.out.println(x.getWeight());
}
}
here is the "Thing" class
public class Thing
{
private int weight;
private String name;
public Thing(int weight,String name){
this.weight = weight;
this.name = name;
}
public void doubleWeight(){
this.weight *= 2;
}
public int getWeight(){
return this.weight;
}
}
finally here is the List class
public class List
{
private Object[] itemList;
private int size;
public List()
{
this.itemList = new Object[10];
this.size = 0;
}
public void insert(Object item){
itemList[size] = item;
size++;
}
public Object getItem(int index){
return itemList[index];
}
}
i need the list to be able to hold objects of any type and not exclusively Thing objects.
i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.
Change that line Thing x = storage.getItem(0); with Thing x = (Thing) storage.getItem(0);
Thing x = (Thing) storage.getItem(0);

Can't print objects stored in HashMap?

I'm working on an assignment for my java class, and we just started learning about HashMaps and we have this assignment where we create enumerated data and store it in a hashmap to print out later. What I can seem to figure out is to be able to print the elements of the HashMap. Here is my project so far:
public class Driver <enumeration>
{
private static HashMap<String, State> stateList = new HashMap<String, State>();
public static void main(String args[]) throws IOException
{
stateList.put("1", State.CA);
stateList.put("2", State.FL);
stateList.put("3", State.ME);
stateList.put("4", State.OK);
stateList.put("5", State.TX);
for(State value : stateList.values())
{
System.out.println(value);
}
}
}
public enum State
{
CA(new StateInfo("Sacramento", 38802500)), FL(new StateInfo("Tallahassee", 19893297)),
ME(new StateInfo("Augusta", 1330089)), OK(new StateInfo("Oklahoma City", 3878051)),
TX(new StateInfo(" Austin", 26956958));
private StateInfo info;
private State(StateInfo info)
{
this.info = info;
}
public StateInfo getInfo()
{
return info;
}
public String toString()
{
return "";
}
}
public class StateInfo
{
private String capital;
private int population;
public StateInfo(String capital, int population)
{
this.capital = capital;
this.population = population;
}
public String getCapital()
{
return capital.toString();
}
public int getPopulation()
{
return population;
}
public String toString()
{
return "";
}
}
Now when I try to run the program, it just terminates without even as much as a reference number for the state objects I'm trying to print. What I think is wrong is in the StateInfo class so I tried changing some things but to no prevail. Can anyone tell me if my suspensions are correct, or am I overlooking something?
You have overridden the toString() method in the State class:
public String toString()
{
return "";
}
Therefore you get no output at all as for every value the toString() method is called in your loop:
for(State value : stateList.values())
{
System.out.println(value);
}
To be more precise: You should get 5 empty lines.
Remove the toString()method in order to use Java's default toString() implementation which returns the classname+hashCode() or make it return e.g. "Capital: " + info.getCapital().

Using dot method in Object type array in Java

Using dot method in Object type array in Java:
class patient {
int id;
public String name;
String pNum;
patient() {
id=0;
name=null;
pNum=null;
}
patient(int i, String n, String p) {
id =i;
name=n;
pNum=p;
}
String getName() {
return name;
}
public String toString() {
String str="ID : "+id+"\n"+"Name : "+name+"\n"+"Phone Number :"+pNum+"\n";
return str;
}
}
When I tried to use it with conventional queue class by q static object I couldn't do so[i].getName(); function or so[i].name; and it gives cannot find symbol error.
like this code below:
static void ShowAllPatient() {
Object [] so=q.toArray();
String str=so[0].getName();
for(int i=0; i<ob.length; i++) {
System.out.println(so[i].name);
}
}
The variable so is of type Object[], the Object doesn't have getName method. The Collection q should define a type of the element, then use
patient[] so=q.toArray(new patient[q.size()]);

Calling a get name method for an object returns null

I have a method that goes through each element in the ArrayList 'Clearance' and if it is an instance of HighClearance I want to add it to a String list of names.
Problem: Whenever I call the getName() method which is in the 'Clearance' superclass, it just returns null and dosent return the name.
public static String peopleClearance (ArrayList<Clearance> clearances) {
String names = "";
for(Clearance c: clearances) {
if(c instanceof HighClearance) {
System.out.println(c.getName()); //tested using sysout statement, just prints ''
names += c.getName();
}
}
return names;
}
In the main method:
Note: The constructor in the Clearance class: public Clearance(String pname)
ArrayList<Clearance> clear= new ArrayList<Clearance>();
clear.add(new HighClearance("Mike"));
clear.add(new HighClearance("John"));
System.out.println(peopleClearance(clear));
Please check with this working example if your superclass/subclass is using the name property right:
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<Clearance> clearances = new ArrayList<>();
clearances.add(new Clearance("C-Tes"));
clearances.add(new HighClearance("H-Test"));
clearances.add(new Clearance("CC-Test"));
clearances.add(new HighClearance("HH-Test"));
System.out.println(peopleClearance(clearances));
}
// changed the parameter to List interface instead of ArrayList
public static String peopleClearance(List<Clearance> clearances) {
String names = "";
for (Clearance c : clearances) {
if (c instanceof HighClearance) {
System.out.println(c.getName()); // tested using sysout statement, just prints ''
names += c.getName();
}
}
return names;
}
}
class Clearance {
private String name;
public Clearance(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
}
class HighClearance extends Clearance {
// if required!
public HighClearance(String name) {
super(name);
}
}

Get the name of enum based on the value [duplicate]

This question already has answers here:
Getting enum associated with int value
(8 answers)
Java getting the Enum name given the Enum Value
(7 answers)
Closed 9 years ago.
I have the following enum
public enum AppointmentSlotStatusType {
INACTIVE(0), ACTIVE(1);
private int value;
private AppointmentSlotStatusType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public String getName() {
return name();
}
}
How do I get the enum name if a value is known for instance 1 ?
For this specific enum it's easy
String name = TimeUnit.values()[1].name();
You can implement a public static method inside the enum, which will give you the enum instance for that id:
public static AppointmentSlotStatusType forId(int id) {
for (AppointmentSlotStatusType type: values()) {
if (type.value == id) {
return value;
}
}
return null;
}
Probably you would also like to cache the array returned by values() in a field:
public static final AppointmentSlotStatusType[] VALUES = values();
then use VALUES instead of values().
Or you can use a Map instead.
private static final Map<Integer, AppointmentSlotStatusType> map = new HashMap<>();
static {
for (AppointmentSlotStatusType type: values()) {
map.put(type.value, type);
}
}
public static AppointmentSlotStatusType forId(int id) {
return map.get(id);
}
You can maintain a Map to hold name for Integer key.
public enum AppointmentSlotStatusType {
INACTIVE(0), ACTIVE(1);
private int value;
private static Map<Integer, AppointmentSlotStatusType> map = new HashMap<Integer, AppointmentSlotStatusType>();
static {
for (AppointmentSlotStatusType item : AppointmentSlotStatusType.values()) {
map.put(item.value, item);
}
}
private AppointmentSlotStatusType(final int value) { this.value = value; }
public static AppointmentSlotStatusType valueOf(int value) {
return map.get(value);
}
}
Take a look at this answer.

Categories

Resources