Java Printing ArrayList of ArrayList - java

I am trying to print my arraylist but i don't know why my printing does not print line by line of IntegerPair in each index of Adjlist:
private ArrayList<ArrayList<IntegerPair>> AdjList; //outer arraylist
private ArrayList<IntegerPair> storeNeighbour; //inner arraylist
private IntegerPair pair;
This is my snippet:
for (ArrayList<IntegerPair> l1 : AdjList) {
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}

The default behavior of ArrayList.toString() is to return a single string containing a (somewhat) beautified list of calls to toString() on each element in the list.
So, long story short: you are almost there; the one thing that is missing:
#Override
public String toString() {
...
within your class IntegerPair.
Like:
public class IntegerPair {
private final Integer first;
private final Integer second;
...
#Override
public String toString() {
return "(" + first + "/" + second ")";
}
or something alike. Without overriding toString() your class will fall back on the default implementation given in java.lang.Object; and that method returns class name + hashcode number (and is thus not so human-readable).

Here :
for (ArrayList<IntegerPair> l1 : AdjList) {
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
You don't differentiate each printed List.
As a result, you will have a series of output without knowing those associated to a same list.
A more readable print would be :
for (ArrayList<IntegerPair> l1 : AdjList) {
System.out.println("ArrayList with :");
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
You don't specify your output. So I don't suppose toString() is or not overridden. If it is not overridden you should either override it to render the String expected here : System.out.println( n + "# ");, or you should specify the content to render here :
System.out.println( n.getOne() + "," + n.getOther() + "# ");
As a side note, toString() is designed for debugging/logging, not for displaying functional messages as an object could be rendered in a way for a case and in another way for other cases.

Related

can i make an arraylist with 2 object from different class?

how can i make an arraylist in the main with 3 itineraries: one without stop (route) and name d1
,one with stop (indirectstop) and name d2, one without stop (route) and name d3.
So ,i ask if there is any way to make an arraylist with two objects from one class and one from other class
Code:
public class Route {
private int id;
private int aeroplane;
private String departure;
private String arrival;
private ArrayList<Ticket> Tickets ;
public Route(){
id = 0 ;
aeroplane = 0 ;
departure = " ";
arrival = " ";
Tickets = new ArrayList<>();
}
public Route(int ID, int aerop, String depar,String arriv,ArrayList<Ticket> tick ){
id=ID;
aeroplane=aerop;
departure=depar;
arrival=arriv;
Tickets=tick;}
public void addTicket(Ticket tick)
{
Tickets.add(tick);
}
#Override
public void finalize(){
Scanner input=new Scanner(System.in);
System.out.println("The id of the train is:");
id=input.nextInt();
System.out.println("The aeroplane code is:");
aeroplane=input.nextInt();
System.out.println("The departure is:");
departure=input.nextLine();
System.out.println("The arrival is:");
arrival=input.nextLine();
#Override
public String toString() {
return "\nID: " + this.getId() + "\nAeroplane: " +this.getAeroplane()
+ "\nDeparture: " + this.getDeparture() + "\nArrival" +this.getArrival() + "Tickets:" +this.getTickets();
}
And IndirectRoute, a subclass of Route.
public class IndirectRoute extends Route {
private String middlestop;
public IndirectRoute()
{
super();
middlestop = "";
}
public IndirectRoute(String middle, int ID, int aerop, String depar,String arriv, ArrayList<Ticket> tick)
{
super(ID,aerop,depar,arriv,tick);
middlestop = middle;
}
public String getMiddlestop() {
return middlestop;
}
#Override
public String toString() {
return super.toString() + "middlestop=" + middlestop + '}';
}
}
Yes, a list may contain objects of a certain type as well as objects of a subclass of that type. Java Generics handles this.
Here is a compact example, all in one .java file.
package work.basil.routing;
import java.util.List;
import java.util.UUID;
public class App
{
public static void main ( String[] args )
{
App app = new App();
app.demo();
}
private void demo ( )
{
List < Route > routes =
List.of(
new Route() ,
new IndirectRoute() ,
new Route()
);
}
}
class Route
{
public final UUID id = UUID.randomUUID();
}
class IndirectRoute extends Route
{
}
When we loop that list, Java can differentiate between elements of the superclass and elements of the subclass.
Current Java
Currently we would use instanceOf to differentiate between elements of the superclass and elements of the subclass
Notice one crucial issue with the following code. We, as the programmer, are responsible for getting the order right. We must consciously test for subclasses before we test for superclasses. The IDE/compiler provide no feedback if we get this order wrong.
for ( Route route : routes )
{
String output = "OOPS! Unexpected type of `route`.";
if ( route instanceof IndirectRoute )
{
output = "Instance of `IndirectRoute`, a subclass of `Route`. " + "Has ID: " + route.id;
}
else if ( route instanceof Route )
{
output = "Instance of `Route`. " + "Has ID: " + route.id;
}
System.out.println( "output = " + output );
}
When run.
output = Instance of `Route`. Has ID: 5a765835-40e4-4cc8-90e7-0687dd7f5362
output = Instance of `IndirectRoute`, a subclass of `Route`. Has ID: b57c9db3-8066-46d6-8f98-0d2d3fa4f835
output = Instance of `Route`. Has ID: a297586b-824e-4520-b760-1aebfd4e3446
Future Java
In the future, we will likely be able to use switch expressions combined with pattern matching for switch to differentiate between elements of the superclass and elements of the subclass. This new approach will be more concise and will provide more clarity of the programmer’s intention.
Notice that unlike the instanceof code seen above, we do get assistance from the IDE/compiler regarding the ordering out our cases. In the code below, if we had Route listed before IndirectRoute, our tooling would indicate the problem and suggest a reordering with the subclass before the superclass.
Caveat: The pattern matching feature is not yet released. Currently previewed in Java 19 (and 18, and 17).
for ( Route route : routes )
{
String output =
switch ( route )
{
case IndirectRoute x -> "Instance of `IndirectRoute`, a subclass of `Route`. " + "Has ID: " + route.id;
case Route y -> "Instance of `Route`. " + "Has ID: " + route.id;
};
System.out.println( output );
}
When run.
Instance of `Route`. Has ID: 07152a33-5b98-4977-a62c-014e9fc3603d
Instance of `IndirectRoute`, a subclass of `Route`. Has ID: 448970bf-2c98-4310-8fff-2dbdac2d68c6
Instance of `Route`. Has ID: e9e7e0cb-0b28-420c-8dba-c2cb72007f2b

Custom annotation for customized toString method, which return first 10 elements from ArrayList

I'm trying to make a custom annotation at class level, to genrate a ToString() method which returns all the field value in a string as they are, but if any field is of type List then we want only first 10 elements from List not whole list (as in lombok it prints whole list).
#Getter
#Setter
public class Entity{
private EntityType type; //type is a string (modifier, getter, setter)
private String entityName;
private String entityValue;
private List<EntityList> entityList; //list retrieve from database can contain 100s of element
#Override
//primarly using for logging purposes
public String toString() {
return "SomeEntity [type=" + type + ", entityName=" + entityName + ", attributeValue="
+ entityValue + ", entityList" = entityList + "]";
}
}
Here toString method is returning all elements of Arraylist, which results a messy logs (if list contains say 1000 elements). To avoid this, I want to use a custom ToString annotation, which generates an toString equivalent at complie time and returns all fields, but if any List type is present then only first 10 elements from list would be returned/printed.
I've tried this
#Override
//primarly using for logging purposes
public String toString() {
return "SomeEntity [type=" + type + ", entityName=" + entityName + ", attributeValue="
+ entityValue + ", entityList" = Utils.toString(entityList) + "]";
}
public class Utils {
private static final int TO_STRING_COLLECTION_LIMIT = 10;
public static <E> String toString(Collection<E> collection) {
if (CollectionUtils.isEmpty(collection)) {
return "<empty>";
} else {
return "{size=" + collection.size() + ", collection=" +
collection.stream().limit(TO_STRING_COLLECTION_LIMIT)
.map(Object::toString).collect(Collectors.joining(",", "[", "]")) +
"}";
}
}
}
but for having an extendable solution I want to create a custom annotation.
How I can create this custom ToString annotation in Spring Boot?
I have checked various online forums but haven't got any relevant information to implement same.
Kindly help.
Thanks

How to traverse through HashSet of objects and print the String value of each object in ToString method?

HashSet<Soldier> soldiers; // it has name, rank, description
#Override
public String toString(){
return "Team: " + teamName + "\n" + "Rank: " + getRanking(soldiers) + "\n"
+ "Team Members Names are: "+"\n" + soldiers.iterator().hasNext();
//last line doesn't work
// I also tried soldiers.forEach(System.out::println) but doesn't work
}
Can anyone please how I can print all the name from Hashset in overriden toString method. Thanks
If you use java 8. It's simple to do with stream API:
public class Test {
public static void main(String[] args) {
Set<String> strings = new HashSet<>();
strings.add("111");
strings.add("113");
strings.add("112");
strings.add("114");
String contactString = strings.stream().map(String::toString).collect(Collectors.joining(","));
}
}
If you want change a delimiter you should replace Collectiors.joining(",") code to what you need. See also documentation by StringJoiner
For your class Soldier which has method getName():
Set<Soldier> soldiers = new HashSet<>();
String soldierNames = soldiers.stream().map(Soldier::getName).collect(Collectors.joining("\n"));
You will get a next result:
Din
Mark
David
... values from the soldiers set
hasNext() does only return a boolean indicating if the Iterator is finished or not.
You still have to call next() (in a loop) to get the next value(s).
See: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

How to print an array within an array of objects

So, i have a class named Hospital and a method called InsertFolders inside the Hospital class.
Inside the method the user must fill an array(max 5) of examinations (I made a class called Folders where i have the set and get methods for the array).
Now i have created another method called print where i want to print this array.
Note that there is an array of objects which contains the Folders.
ListOfFolders[i].getNameOfFolder(this is the field of the folder's name for example).
Is there a way where i can print the array?
For example when i try ListOfFolders[i].getArrayOfExaminations() it doesn't print the expected examinations.
Just override toString function like:
public class Person{
private int id;
private String firstName;
private String lasrName;
.
.
public Person(){
this.id = 1;
this.firstName = "First Name";
this.lastName = "Last Name";
}
public String toString(){
String str = "";
str += "Person Info: \n";
str += "Id : " + id + "\n";
str += "First Name : " + firstName + "\n";
str += "Last Name : " + lastName + "\n";
....
return str;
}
}
If you would share us your code I would have implement it better, but this is the idea.
Usage:
List<YourClass> list = new ArrayList<YourClass>();
list.add(new Person());
for (YourClass item : list){
System.out.println(item); //here it will automaticly use the overridden toString in your class
}
Output:
Person Info:
Id: 1
First Name
Last Name
Just printing an object prints the reference (~address) to it by default. You need to override the toString() method for the object to make it print the proper value.
If this is the default array in Java, you can loop over the objects in the array with the for(item : array) syntax.

java.util.<>Hashset cannot be converted to boolean

I have an error in this code
public Hotel()
{
occupiedRooms = new HashSet<Room>();
PapersOrdered = new HashMap <String,ArrayList<String>>();
}
public String getGuest(String roomNo)
{
for (Room room; occupiedRooms;)
{
if(room.getRoomNo().equals(roomNo)) return room; getGuest();
return "room " + roomNo + " is not occupied" ;
}
}
and the occupied rooms gets an error saying java.util.<>Hashset cannot be converted to boolean,
what is the best way to correct this.(All code is not in here but just what is relevant)
Yes, a HashSet is not a boolean and cannot be converted to a boolean, and the regular for loop expects a boolean expression in the middle section (the section that determines when the loop terminates).
If you want to iterate over all the values in the set, you can use the enhanced for loop :
for (Room room : occupiedRooms)
{
if(room.getRoomNo().equals(roomNo))
return room;
getGuest();
return "room " + roomNo + " is not occupied" ;
}
Not sure how much sense your for loop makes, though, as it would always return something after the firstroom is tested, so the remaining rooms won't be checked.

Categories