I want to know how to print a List in Java where in each position there is a String and an int.
List pasajeros = new ArrayList();
I insert the data like this:
public void insert(List a) {
System.out.print("Name: ");
name= sc.nextLine();
System.out.print("Number: ");
number= sc.nextInt();
ClassName aero = new ClassName(name, number);
a.add(aero);
}
}
And it seems to work like this, but in the syso gives me an error.
So you have a list of ClassName.
To print them, you can simply use a for loop:
List<ClassName> pasajeros = new ArrayList<>();
// + insert elements
for (ClassName cn : pasajeros) {
System.out.println("Name: " + cn.getName() + ", number: " + cn.getNumber());
}
You are printing an object without overriding the toString method..
list.Aerolinea#154617c means you are printing the objects hashcode..
so your problem is not at inserting, is at printing out the objects that the list is holding, in this case your Aerolinea class must override properly the toString method.
something like:
class Aerolinea {
private String nombre;
private String apellido;
#Override
public String toString() {
return "Aerolinea [nombre=" + nombre + ", apellido=" + apellido + "]";
}
}
Try like put method toString in your class...
public class Aerolinea {
String nombre;
.......
.......
public String toString() {
return "nombre" = nombre;
}
}
Ok I fixed it finally, it was silly...
I forgot to write < ClassName> in the method. Here is the final code
public void vertodo(List<Aerolinea> a) {
for (Aerolinea cn : a) {
System.out.println("Name: " + cn.name+ " ID: " + cn.id);
}
}
since I had created it like List pasajeros = new ArrayList();, then I changed it to List<Aerolinea> pasajeros = new ArrayList();.
Although I can't write the final <> empty after ArrayList as some have recommended.
Related
LOG I am getting
Hibernate: select * from resource_hierarchy
com.att.dmp.entity.ResourceHierarchy#7380c27
Instead of com.att.dmp.entity.ResourceHierarchy#7380c27, I want the actual list something like ResourceHieracy [ ID = 1, name = Apple, product = Banana]
List<com.att.dmp.entity.ResourceHierarchy> list = hesourceHierarchyRepository.findAOI();
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
#Repository
public interface ResourceHierarchyRepository extends JpaRepository<ResourceHierarchy, String> {
#Query(value="select * from resource_hierarchy ", nativeQuery=true)
List<ResourceHierarchy> findAOI();
}
When you print something it actually calls the toString() method of the class. If you want to print something else, lets say the variables of class, override the toString() method of ResourceHierarchy class and return the value of variables from the method as String. And it will print your expected values. Something like:
public class ResourceHierarchy {
private String id;
private String name;
private String product;
#Override
public String toString() {
return "ResourceHierarchy[" +
"id = " + id +
"name + " + name +
"product + " + product +
"]";
}
}
Or alternatively you can use lambok to auto-generate toString() code for you.
I need to print the name of the shop (this method is in the Shop class) as well as the product name (which is an arraylist) and the price of the product ( which is done using a getter from the class Product). I want to loop through all the products in the arraylist, how can I do that ?
Please if something is not clear comment it and I will edit the question to make it clearer.
public String toString()
{
for(int i=0; i<products.size();i++)
{
return "Shop"+"["+"name"+" = "+name+","+"Product name"+" = "+products.get(i).getName()+", "+"Price"+" = "+products.get(i).getPrice()+"]";
}
return null;
}
This is wrong as the i++ is a dead code which means that the loop will execute once. Any help please ?
Thanks for your time
Use StringBuilder:
public String toString() {
StringBuilder sb = new StringBuilder("Shop").append("[name = ").append(name)
for (Product product : products) {
sb.append(",")
.append("Product name = ").append(product.getName())
.append(", Price = ").append(product.getPrice())
.append("]");
}
return sb.toString();
}
Note:
Do not use + inside the loop to join strings (as accepted answer did) as it will create a stringbuilder in each iteration to join the strings, and then append it to the outer stringbuilder.
Using a return statement will end the function's execution. Here's what you want to do instead.
public String toString()
{
StringBuilder result = new StringBuilder();
result.append("Shop [ name = "+name+" ");
for(Product p : products)
{
result.append("Product name"+" = "+p.getName()+", "+"Price"+" = "+p.getPrice()+" ");
}
result.append("]");
return result.toString();
}
You could use StringJoiner ( https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html )
public String toString(){
StringJoiner string = new StringJoiner(", ", name + "[", "]");
for (Product p : list) {
string.add("Product name:" + p.getName()).add("Product value:"+p.getValue());
}
return string.toString();
}
Output:
Shop[Product name:Teste, Product value:1.0, Product name:teste2, Product value:2.0]
You can use Guava Objects Class it facilitates to build the object toString().They changed it recently to MoreObjects.ToStringHelper
public String toString(){
ToStringHelper toStringHelper = MoreObjects.toStringHelper(this);
for (Product p : products)
{
toStringHelper.add("name", p.name);
toStringHelper.add("Product name", p.getName();
}
return toStringHelper.toString();
}
If you have a small collection, you can always just concatenate strings with +.
Creating a StringBuilder provides unnecessary overhead for small examples.
Other than that, compiler will optimise that part of code If it provides improvement to the performance.
public String toString() {
String str = "Shop [name = " + name + " ";
for (Product product : products) {
str += ", Product name = " + product.getName();
str += ", Price = " + product.getPrice() + "]";
}
return str;
}
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I have an array that I need to print, and I've already looked through stackoverflow so I know that I need to use toString so that I don't just print the hashcode, but for some reason it's still printing stuff like "music2.Music2#4162b8ce, music2.Music2#3852fdeb, music2.Music2#509c6c30"
Music2[] musiclist = new Music2[10];
musiclist[0] = new Music2("Pieces of You", "1994", "Jewel");
musiclist[1] = new Music2("Jagged Little Pill", "1995", "Alanis Morissette");
musiclist[2] = new Music2("What If It's You", "1995", "Reba McEntire");
musiclist[3] = new Music2("Misunderstood", "2001", "Pink");
musiclist[4] = new Music2("Laundry Service", "2001", "Shakira");
musiclist[5] = new Music2("Taking the Long Way", "2006", "Dixie Chicks");
musiclist[6] = new Music2("Under My Skin", "2004", "Avril Lavigne");
musiclist[7] = new Music2("Let Go", "2002", "Avril Lavigne");
musiclist[8] = new Music2("Let It Go", "2007", "Tim McGraw");
musiclist[9] = new Music2("White Flag", "2004", "Dido");
public static void printMusic(Music2[] musiclist) {
System.out.println(Arrays.toString(musiclist));
}
This is my array and the method that I am using to print it. Any help would be appreciated.
You should define toString() method in your Music2 class and print it in the way you like. I don't know how fields in your object are named exactly, but it can look like this:
public class Music2 {
...
#Override
public String toString() {
return this.artist + " - "+ this.title + " (" + this.year + ")";
}
}
After that your printMusic method will work as expected.
You can declare a for each loop to display the property of music. This is the code
for (Music2 music : musiclist){
System.out.println("Title: " + music.getTitle);
}
Because by default Arrays got toString() implementation of the Object class, that is:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So you need to overwrite toString() in your Class
#Override
public String toString() {
return this.fieldNameone + " "+ this.fieldNametwo + " " + this.fieldNamethree + " ";
}
If using Java8 you can use
Arrays.stream(musiclist).forEach(System.out::print)
but make sure that Music2 has an overriden method for toString()
In the Arrays.toString(musiclist) you are actually invoking toString() on each element of the array to compose the resulting string. So, if you override the basic Object toString() implementation in Music2 class you will get what you want
public class Music2 {
.....
#Override
public String toString() {
return "Music2{" + "title=" + title + ", group=" + group + ", year=" + year + '}';
}
}
So arrayLists are a first for me, and as far as I know I've been doing everything correctly and following the examples provided to me by my online course. HOWEVER, for some reason or other I have a line underlined red...which I will get to in a moment after a brief explanation of this program.
This program allows you to input an employee information and after pressing the 'list' button (listButton) it outsput in the employeeField etc etc. That basically sums up this program.
public class EmployeeView extends FrameView {
class Company { //this is the class to allow me to put 'company' in the arrayList...
String ID, firstName, lastName, annualSal, startDate, mileage;
Company (String _ID, String _firstName,String _lastName, String _annualSal, String _startDate) {
ID = _ID;
firstName = _firstName;
lastName = _lastName;
annualSal = _annualSal;
startDate = _startDate;
}
}
/** Define the ArrayList */
ArrayList <Company> inventory = new ArrayList <Company>();
private void AddActionPerformed(java.awt.event.ActionEvent evt) {
String c;
String ID, firstName, lastName, annualSal, startDate;
ID = IDField.getText(); //all this stuff grabs info from the Fields...which will then be stored in the array
firstName = firstNameField.getText();
lastName = lastNameField.getText();
annualSal = annualSalField.getText();
startDate = startDateField.getText();
The two lines below this is the culprit. I suppose "new" is't nessisary but it was there in the example so that's why I am using it...however when I get rid rid of it only 'company' is underlined and the 'c' in the 2nd line is underlined instead of having the entire line underlined. Anyways I hope this is making sense...since its (from what I know of) my only problem.
c = new Company(ID, firstName, lastName, annualSal, startDate);
inventory.add(c);
}
private void ListActionPerformed(java.awt.event.ActionEvent evt) {
String temp="";
for (int x=0; x<=inventory.size()-1; x++) {
temp = temp + inventory.get(x).ID + " "
+ inventory.get(x).firstName + " "
+ inventory.get(x).lastName + " "
+ inventory.get(x).annualSal + " "
+ inventory.get(x).startDate + "\n";
}
employeeTArea.setText(temp);
}
You've declared c to be a String; you can't assign a Company directly to a String.
Change your declaration of c to be Company.
c is declared as a String above. It should be type Company instead.
I am adding information from main()
I am adding different information for CD, DVD, book..
I have 3 separate classes - item has 3 classes in it...
project - main()
Library - this function does all the adding
Item(cd,dvd,book) inheritance
For Music i am adding band info, title info, keywords, and members..
I am adding members separately than of the other info..
As you can see the members is not outputing correctly as the others..
>>> music CDs:
-Music-
band: Jerry Garcia Band
# songs: 15
members: [Ljava.lang.String;#61de33
title: Don't Let Go
C:\Java\a03>
I am using the same toString() function for members as i am the rest, so i am not sure why it would do this..
I will give you as much info as i think you need to see..
Main() - as you can see it calls 2 different functions.
the addbandmembers is where i am having problems...
out.println(">>> adding items to library:\n");
item = library.addMusicCD("Europe In '72", "Grateful Dead", 12, "acid rock", "sixties", "jam bands");
if (item != null) {
library.addBandMembers(item, "Jerry Garcia", "Bill Kreutzman", "Keith Godcheaux");
library.printItem(out, item);
}
in Library class - here is the addbandmember function ..
Could this be the cause??
public void addBandMembers(Item musicCD, String... members)
{
((CD)musicCD).addband(members);
}
In the Items class here is the function addband - tostring()
here is the CD class which extends the items class..
class Item
{
private String title;
public String toString()
{
String line1 = "title: " + title + "\n";
return line1;
}
public void print()
{
System.out.println(toString());
}
public Item()
{}
public Item(String theTitle)
{
title = theTitle;
}
public String getTitle()
{
return title;
}
}
class CD extends Item
{
private String artist;
private String [] members;
private int number;
public CD(String theTitle, String theBand, int Snumber, String... keywords)
{
super(theTitle);
this.artist = theBand;
this.number = Snumber;
}
public void addband(String... member)
{
this.members = member;
}
public String getArtist()
{
return artist;
}
public String [] getMembers()
{
return members;
}
public String toString()
{
return "-Music-" + "\n" + "band: " + artist + "\n" + "# songs: " + number + "\n" + "members: " + members + "\n" + "\n" + super.toString() + "\n";
}
public void print()
{
System.out.println(toString());
}
}
I do have other information in the items class like a nook class, movie class that i didnt show. I would like to keep everything the way i have it set up..
So, if the other items are printing fine than maybe its the cast in the addbandmember function thats giving me problems?
members is printing the way it is since it's an array (you can tell this by the fact its output as members: [Ljava.lang.String;#61de33 ).
Instead you need to iterate through it and print each element.
e.g.
for (String member : members) {
...
}
The simplest way is to use Arrays.toString(). Alternatively append to a StringBuilder and then print to this. You can be cleverer, and use StringUtils.join() from Apache Commons Lang, which will give you more control.
Arrays don't have a useful toString() implementation. You can print out the members in a loop or use the Arrays.toString() method to do this for you:
return "-Music-" + "\n"
+ "band: " + artist + "\n"
+ "# songs: " + number + "\n"
+ "members: " + Arrays.toString(members) + "\n"
+ "\n"
+ super.toString() + "\n";