strange output from ArrayList [duplicate] - java

This question already has answers here:
what is the number that it shows when I print out the **this** pointer in java?
(9 answers)
Closed 7 years ago.
I'm new to Java and i'm having an issue with objects in ArrayList.
I'm trying to put a object with a text and a timestamp in a ArrayList.
At the start it behaves correctly, so you can type your notes in and if you type "exit" it closes the Input and shows all entries from the ArrayList.
But if i type "exit" it just shows me this output:
Notizblock#4c15c0d7
This is my code:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import java.util.ArrayList;
class Notizblock {
//heutiges Datum erzeugen
private static String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyy HH:mm:ss");
Date datum = new Date();
return dateFormat.format(datum);
}
private String text;
private String datum;
//Konstruktor
public Notizblock(String text, String datum){
this.text = text;
this.datum = datum;
}
public void print() {
System.out.println("Datum: "+datum+" Text: "+text);
}
public static void main(String[] args) {
ArrayList<Notizblock> notizen = new ArrayList<Notizblock>();
Scanner eingabe = new Scanner(System.in);
while (true) {
System.out.println("Notiz eingeben:");
String a = eingabe.next();
if (a.equals("exit")) {
break;
}
notizen.add(new Notizblock(a, getDateTime()));
}
System.out.println("alle notizen:");
for (Notizblock notiz :notizen ) {
System.out.println(notiz);
}
}
}
I'm glad if anyone could tell me what i'm doing wrong, I'm open for every improvment to my code.
Hit me up if you need some more Information.
Thanks
P.S. I'm german, sorry for my bad english ;)

You need to override toString method. The Notizblock is a custom class, the default System.out will be classname#hashcode of the object, which is what you are seeing.
once you override the toString it will print the content of the object as per your toString implementation. Here is a sample:
#Override
public String toString() {
return "Notizblock {" +
"text='" + text + '\'' +
", datum='" + datum + '\'' +
'}';
}
Yes. You can call the existing print method which you have defined.
System.out.println("alle notizen:");
for (Notizblock notiz :notizen ) {
System.out.println(notiz.print());
}
The toString() is called automatically when you print (SOUT) anything. That is why overriding toString() will be a better approach then providing a custom method for doing the same job, unless you are doing some extra/special formatting of the data.

Related

Why is my TreeSet in Java giving me a null pointer exception when I try to add a String? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 11 months ago.
I'm working on a project for a Java class, and I can't seem to get past this NullPointerException. The project is a command-line LinkedIn program. One of the aspects I'm implementing is the ability to add a skillset to a user's profile.
I have a LinkedInUser class in which I define a TreeSet to hold these skillsets in the form of Strings entered by the user. I'm using TreeSet, because the assignment requires them to be sorted.
I define the TreeSet in the LinkedInUser class here:
private Set<String> skillsets = new TreeSet<>();
The action the user takes is defined in the AddSkillsetAction class:
String skillset;
System.out.println("Enter a skillset to add to your list:");
skillset = scanner.nextLine();
loggedInUser.addSkillset(skillset);
System.out.println(skillset + " has been added to your skillsets.");
And the String they enter is passed to the addSkillSet function in the LinkedInUser class:
public void addSkillset(String skillset) {
skillsets.add(skillset);
}
I keep getting a NullPointerException on the line:
skillsets.add(skillset);
What am I doing wrong? I've tested every level up to that line. I even tested the TreeSet inside the addSkillset function with this code:
if(skillsets == null) {
System.out.println("The TreeSet is null.")
}
It's telling me the TreeSet is null. I thought instantiating the Set with:
private Set<String> skillsets = new TreeSet<>();
would actually create an empty TreeSet, instead of it pointing to a null location. Why is my set "skillsets" still pointing to null? What am I doing wrong here?
EDIT:
Here are the full classes:
package edu.institution.asn2;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class LinkedInUser extends UserAccount implements Comparable<LinkedInUser>, Serializable {
private static final long serialVersionUID = 75648957489235739L;
private String type;
private List<LinkedInUser> connections = new ArrayList<>();
private Set<String> skillsets = new TreeSet<>();
public LinkedInUser(String username, String password) {
super(username, password);
}
#Override
public void setType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
// Add a connection to user's list
public void addConnection(LinkedInUser user) throws LinkedInException {
int index = connections.indexOf(user);
if (index >= 0) {
throw new LinkedInException("You are already connected with this user.");
}
else {
connections.add(user);
}
}
// Remove a connection from the user's connection list
public void removeConnection(LinkedInUser user) throws LinkedInException {
int index = connections.indexOf(user);
if (index < 0) {
throw new LinkedInException("You are NOT connected to this user.");
}
else {
connections.remove(index);
}
}
// Return a copy of the ArrayList of connections
public List<LinkedInUser> getConnections() {
ArrayList<LinkedInUser> copy = new ArrayList<>(connections);
return copy;
}
// Return the number of connections
public int getNumberOfConnections() {
return connections.size();
}
// Return the skillsets
public Set<String> getSkillsets(){
return skillsets;
}
// Add a skillset
public void addSkillset(String skillset) {
skillsets.add(skillset);
}
// Remove a skillset
public void removeSkillset (String skillset) {
if(skillsets.contains(skillset)){
skillsets.remove(skillset);
} else {
System.out.println(skillset + " is not in your skills list.");
}
}
// Override the compareTo function
#Override
public int compareTo(LinkedInUser user) {
int i = this.getUsername().compareToIgnoreCase(user.getUsername());
return i;
}
}
And the class to add a skillset:
package edu.institution.actions.asn7;
import java.util.Scanner;
import edu.institution.ApplicationHelper;
import edu.institution.UserRepository;
import edu.institution.actions.MenuAction;
import edu.institution.asn2.LinkedInUser;
public class AddSkillsetAction implements MenuAction {
#Override
public boolean process(Scanner scanner, UserRepository userRepository, LinkedInUser loggedInUser) {
String skillset;
System.out.println("Enter a skillset to add to your list:");
skillset = scanner.nextLine();
loggedInUser.addSkillset(skillset);
System.out.println(skillset + " has been added to your skillsets.");
ApplicationHelper.incrementSkillsetCount(skillset);
return true;
}
}
After I run and try to add a skillset, I get this error:
Exception in thread "main" java.lang.NullPointerException
at edu.institution.asn2.LinkedInUser.addSkillset(LinkedInUser.java:69)
at edu.institution.actions.asn7.AddSkillsetAction.process(AddSkillsetAction.java:19)
at edu.institution.ApplicationController.process(ApplicationController.java:61)
at edu.institution.LinkedInCLI.main(LinkedInCLI.java:39)
LinkedInUser.java:69 is:
skillsets.add(skillset);
By the way… Your naming is confusing. String skillset; should be String skill, and .addSkill not .addSkillset, because you are adding individual skills rather than adding a set.
Clarifying your naming may clarify your code. Notice the singular skill and plural skills naming used in code below.
You did not provide enough details to diagnose the problem. But I can show you some example code based on your descriptions.
Your problem may be related to your not properly instantiating the TreeSet. Notice in this code that you have a choice of at least two places in which to instantiate:
On the declaration line of skills.
In the constructor. (Code currently commented-out.)
The LinkedInUser class.
package work.basil.linkedin;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
public class LinkedInUser
{
private String name;
private NavigableSet < String > skills = new TreeSet <>();
// Constructor
public LinkedInUser ( final String name )
{
this.name = name;
// this.skills = new TreeSet <>() ;
}
// Modifiers
public void setName ( String name ) { this.name = name; }
public void addSkill ( String skill ) { this.skills.add( skill ); }
// Getters
public String getName ( ) { return name; }
public Set < String > getSkills ( ) { return Set.copyOf( this.skills ); } // Return a unmodifiable copy of the set. (defensive programming)
}
For defensive programming, we return a copy of the set. This unmodifiable copy returned by Set.copyOf has no order. In some implementations, the order may even change arbitrarily for each iterator. If you want to return an ordered NavigableSet instead, do this:
Change the return type of the method to NavigableSet.
Change the code to pass the instance’s set to the constructor of another set.
public NavigableSet < String > getSkills ( ) { return new TreeSet <>(this.skills ); }
Usage.
LinkedInUser alice = new LinkedInUser( "Alice" );
LinkedInUser bob = new LinkedInUser( "Bob" );
alice.addSkill( "Yodeling" );
alice.addSkill( "Tap Dancing" );
bob.addSkill( "Juggling" );
System.out.println( alice.getName() + " does " + alice.getSkills() );
System.out.println( bob.getName() + " does " + bob.getSkills() );
System.out.println( List.of( alice , bob ) );
When run.
Alice does [Yodeling, Tap Dancing]
Bob does [Juggling]
[LinkedInUser{name='Alice', skills=[Tap Dancing, Yodeling]}, LinkedInUser{name='Bob', skills=[Juggling]}]
You said:
I thought instantiating the Set with:
private Set<String> skillsets = new TreeSet<>();
Yes, that would indeed instantiate a TreeSet object, and store a reference to that set in a variable named skillsets. I expect you are placing that code in the wrong location. Again, look at the two locations I suggested earlier in this Answer: on declaration line, or in constructor.

adding into an Array list of objects from a text file in java

i thinkj i have a type argument problem which im really confused about, Ive started with an Arraylist which, extends to the another class with my main methods. and i have a Events class, which i want to categorize from the txt file, the main problem i have is adding from my txt file which iread into an ArrayList, java pops up with this error message
incompatible types: java.lang.String cannot be converted to CSC8012.Events
But in my events it has String? Im really confused
This is my generic arraylist i think?
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable> extends
ArrayList<E> {
public void insert(E e) {
this.add(e);
int lastIndex = 0;
for( lastIndex = this.size() -1 ; lastIndex > 0 && this.get(lastIndex-1).compareTo(e) > 0 ; lastIndex--){
this.set(lastIndex, this.get(lastIndex-1));
}
this.set(lastIndex,e);
}
}
Heres my events class objects
public class Events implements Comparable<Events>{
//fields setting up the variables
String ticketsbought;
String eventname;
public Events(String ticketsbought, String eventname ){
this.ticketsbought = ticketsbought;
this.eventname = eventname;
}
#Override
public int compareTo (Events E){
return
ticketsbought.compareTo(E.getTicketsbought()) + eventname.compareTo(E.getEventname());
}
public String getTicketsbought() {
return ticketsbought;
}
public String getEventname() {
return eventname;
}
//setting it up for the main method from the constructor fields above
public void setTicketsbought(String ticketsbought) {
this.ticketsbought = ticketsbought;
}
public void setEventname(String eventname) {
this.eventname = eventname;
}
#Override
public String toString()
{
return "Tickets bought " + this.ticketsbought + "Event name " + this.eventname;
}
}
My main menu class
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Objects;
import java.util.ArrayList;
import java.util.Collections;
java.util.Scanner;
public class MainProgram extends SortedArrayList{
public static void main(String[] args) throws FileNotFoundException{
boolean bye = false;
String line;
String option;
Scanner sc = new Scanner(System.in); //tos take in our input
do{
System.out.println("Choose an option.."); // heres our options
System.out.println("e Information on all events");
System.out.println("c All information on clients");
System.out.println("f to quit");
System.out.println("b to update when tickets are bought by a registered Client");
System.out.println("r to update the stored data when a Client cancels a ticket");
option = sc.nextLine();
switch (option) { // these are splitting our inputs to these cases with different outcomes
case "e":
//System.out.println("information on events");
Scanner inFile = new Scanner(new FileReader("input.txt"));
// Other declarations// Reading and processing the input data// Printing out the results outFile.close();
ArrayList<Events> events = new ArrayList<>();
while(inFile.hasNextLine()) {
String data = inFile.next();
events.add(data);//error based on these? Event is based off of arraylist<E> and inherits from those whilst i have them as string?
You are seeing the exception because of Generics in Java.
Your ArrayList is declared to take Events objects.
ArrayList<Events> events = new ArrayList<>();
However, you are trying to add a String object to it.
String data = inFile.next();
events.add(data); //Cannot add a String object, only Events object allowed.
One way to fix this is to create an Events object using the String, and then add to the Arraylist. I am assuming each line has Event name and String in it, separated by a comma.
//Get your event name and tickets from the String data.
String tokens[] = data.split(",");
String eventName = tokens[0];
String ticketsBought = tokens[1];
//create an events object
Events eventObj = new Events(eventName, ticketsBought);
//Now add to your arraylist.
events.add(eventObj);
As an aside, you do not need to extend SortedArrayList in MainProgram. The main class is usually top level class in your project, and it will only contain objects (this is a common practice). If you want to use the new logic you have added in SortedArrayList, then instead of creating ArrayList<Events> events = new ArrayList<>();, you can create SortedArrayList<Events> events = new SortedArrayList<>();

Serialize an object into a string [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
Can someone help me to serialze an object into a string? The result of my code is a bit weird, I need to get a toString(); methode or something with which i can serialze an object into a string but I dont know any.
Thanks for the help
results with getString -> only "null"
result without getString(); -> Fruit#4dd8dc3, Fruit#6d03e736, Fruit#568db2f2, Fruit#378bf509, Fruit#5fd0d5ae,
Fruit#2d98a335, Fruit#16b98e56, Fruit#7ef20235"
import java.io.Serializable;
public class Fruit implements Comparable<Fruit>,Serializable{
String getString;
String name;
int gewicht;
public String getString() {
return this.getString;
}
public Fruit(String name, int gewicht) {
this.name=name;
this.gewicht=gewicht;
}
public int compareTo(Fruit otherFruit) {
if(this.gewicht < otherFruit.gewicht)
return -1;
if(this.gewicht>otherFruit.gewicht)
return 1;
return 0;
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.TreeSet;
public class FruitTree {
public static void main(String[] args) {
TreeSet<Fruit> fruitTree = new TreeSet<Fruit>();
fruitTree.add(new Fruit("Kiwi",5));
fruitTree.add(new Fruit("Kirsche",1));
fruitTree.add(new Fruit("Ananas",75));
fruitTree.add(new Fruit("Zitrone",15));
fruitTree.add(new Fruit("Grapefruit",44));
fruitTree.add(new Fruit("Banane",55));
fruitTree.add(new Fruit("Kirsche",2));
fruitTree.add(new Fruit("Kiwi",8));
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("IO.txt"));
Iterator<Fruit> it = fruitTree.iterator();
while(it.hasNext()) {
oos.writeObject(it.next());
}
oos.writeObject(null);
ObjectInputStream ois = new ObjectInputStream (new FileInputStream("IO.txt"));
Object readObject=null;
TreeSet<Fruit> deserializedFruits= new TreeSet<Fruit>();
do {
readObject=ois.readObject();
if(readObject !=null)
deserializedFruits.add((Fruit) readObject);
}
while (readObject!=null);
it=deserializedFruits.iterator();
while(it.hasNext()) {
System.out.println(it.next().getString());
ois.close();
oos.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Can someone help me to serialze an object into a string? The result of my code is a bit weird, I need to get a toString(); methode or something with which i can serialze an object into a string but I dont know any.
Thanks for the help
Adding implements Serializable to your class will not override default Object.toString implementation - that's not how Java works (btw this default implementation will actually provide you what you got - for example Fruit#5fd0d5ae - that's how it works)
what you need to do is to override toString by yourself - for example
public class Fruit implements Comparable<Fruit>,Serializable {
// ...
#Override
public String toString() {
return "name: " + this.name + ", gewicht: " + String.valueOf(this.gewicht);
}
}
or to use some existing tool that will generate this method for you (like lombok), or even better that will allow you to serialize your class object to some common format like JSON or XML (for this take a look at gson or Jackson)

How to store objects in ArrayList and print it? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
for loop without braces in java
(6 answers)
Closed 4 years ago.
i am working in my project and it is about a clinic , my class is appointment , and i have to let the user to enter the day, time, section, doctor name, patient name. and store it an ArrayList
i wrote the code but when i run the project there is no output and i don't know why :(
package appointments;
import java.util.Scanner;
import java.util.ArrayList;
public class Appointment {
public static void main(String[] args) {
ArrayList<Object> appointments = new ArrayList<>();
Scanner input = new Scanner (System.in);
System.out.println("enter day, time, section , doctor , you name in order to book appointment : ");
appointment xx = new appointment();
for (int i=0; i<5; ++i)
xx.setAppDay(input.nextLine());
xx.setAppTime(input.nextLine());
xx.setAppSection(input.nextLine());
xx.setAppDoctor(input.nextLine());
xx.setAppPatient(input.nextLine());
appointments.add(xx);
System.out.println(appointments);
}
public static class appointment {
public String appDay;
public String appTime;
public String appSection;
public String appDoctor;
public String appPatient;
public appointment(String appDay, String appTime, String appSection, String appDoctor, String appPatient) {
this.appDay = appDay;
this.appTime = appTime;
this.appSection = appSection;
this.appDoctor = appDoctor;
this.appPatient = appPatient;
}
public appointment() {
}
public void setAppDay(String appDay) {
this.appDay = appDay;
}
public void setAppTime(String appTime) {
this.appTime = appTime;
}
public void setAppSection(String appSection) {
this.appSection = appSection;
}
public void setAppDoctor(String appDoctor) {
this.appDoctor = appDoctor;
}
public void setAppPatient(String appPatient) {
this.appPatient = appPatient;
}
public String getAppDay() {
return appDay;
}
public String getAppTime() {
return appTime;
}
public String getAppSection() {
return appSection;
}
public String getAppDoctor() {
return appDoctor;
}
public String getAppPatient() {
return appPatient;
}
}
}
Your loop has no braces and you only instantiate one appointment. You wanted something like,
for (int i = 0; i < 5; ++i) {
appointment xx = new appointment();
xx.setAppDay(input.nextLine());
xx.setAppTime(input.nextLine());
xx.setAppSection(input.nextLine());
xx.setAppDoctor(input.nextLine());
xx.setAppPatient(input.nextLine());
appointments.add(xx);
}
Then you need to override toString() in appointment.
Currently the same appointment object is being added to the list, so the list would only have a single entry in it.
So move the object creation and addition to the list along with setting the appointment fields inside the for loop. Please add the curly braces correctly as currently only the
xx.setAppDay(input.nextLine())
is part of the for loop.
Also appointment shouldn't be a static class multiple objects need to be created.
You need to implement a toString() Method for this purpose. And print it like this.
public String toString(){
return this.appDay; // return the output you want, so build a String using your attributes
}
System.out.println(Arrays.toString(appointments));
Edit: And do what Elliott Frisch said.

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;
}
...
}

Categories