Java printing an array of objects - java

I know there are a lot of pages about this question, but I cannot understand it in my case.
I need to print the array of objects. For example, I have an array of objects that hold objects from the "shape" class. Do I call the toString method for each object in the array, or do I code the toString method in ObjectList to print out the instance variables? If so, how do I do that?
public class Shape{
private String shapeName;
private int numSides;
public String toString(){
return shapeName + " has " + numSides + " sides.";
}
}
public class ObjectList{
private Object[] list = new Object[10];
private int numElement = 0;
public void add(Object next){
list[numElement] = next;
}
public String toString(){
// prints out the array of objects
// do I call the toString() method from the object?
// or do I print the instance variables? What am I printing?
// I'm guessing I do a for loop here
}
}
public class Driver{
public static void main(String[] args){
ObjectList list = new ObjectList();
Shape square = new Shape("square", 4);
Shape hex = new Shape("hexagon", 6);
list.add(square);
list.toString(); // prints out array of objects
}
I am aiming for it to print this:
square has 4 sides
hexagon has 6 sides

The simplest way to do this is use Arrays.toString:
Arrays.toString(myArray);
This will internally call the toString method of every element of your array.
So just override toString method in your Shape class and it should work fine.
To add further, override toString method in your class where you call Arrays.toString on your variable list :
public class ObjectList{
private Object[] list = new Object[10];
.............
public String toString(){
return Arrays.toString(list);
}
}

You can do this with bellowed code, make for loop in toString method to print each shape object.
class Shape{
private String shapeName;
private int numSides;
Shape(String shapeName, int numSides){
this.shapeName = shapeName;
this.numSides = numSides;
}
public String toString(){
return shapeName + " has " + numSides + " sides.";
}
}
class ObjectList{
private Object[] list = new Object[10];
private int numElement = 0;
public void add(Object next){
list[numElement] = next;
numElement++;
}
#Override
public String toString(){
String str="";
int i=0;
while(list[i] != null){
str += list[i]+"\n";
i++;
}
return str;
}
}
public class Driver{
public static void main(String[] args){
ObjectList list = new ObjectList();
Shape square = new Shape("square", 4);
Shape hex = new Shape("hexagon", 6);
list.add(hex);
list.add(square);
System.out.println(list);
}
}

Write a for-each statement in toString() of Object List and create a large String with '\n' characters and return it as a String . Or may be name displayListElement() will be semantically more correct in which you can simple print all the Objects in the list .

Indeed, you should call toString method for each of objects that you want to print and join them together. You can use StringBuilder to hold the string-in-the-making as follows:
public String toString() {
StringBuilder result = new StringBuilder();
for (int i = 0; i <= numElements; i++) {
result.append(list.toString() + "\n");
}
return result.toString();
}
Note that you need to increase numElements (e.g. numElements++) for each add operation as what pbabcdefp said in the comments. Also, you can use ArrayList class to manage "growing arrays".

Related

Return different datatypes in a method in java

I have a very silly question in java. I have a main method which in turns calls a method passing one string value. But in return I need to get 3 string values. Can someone please assist?
In main method, I pass only one string value and it has to return 3 string or may be at times 2 string and one int.
public static void main(String[] args) {
List <String> ls= cusmethod("string1");
ls.get(0); //get string A
}
Private static string cusmethod(String test)
{
String A = "A"+test;
String B = "B"+test;
String C = "C"+test;
// Need to return all these 3 string to main method.
return A , B, C;
}
The method should return the 3 string values to the main method. Please advise how to achieve this. I am not sure how to return these strings to main method and how to retrieve these string in main
Try returning a list in your helper method:
private static List<String> cusmethod(String test) {
List<String> list = new ArrayList<>();
list.add("A" + test);
list.add("B" + test);
list.add("C" + test);
return list;
}
You cannot return more then one value in java. You can wrap your result in a class and return that class.
If you need to return n values of the same type you can create a List or an array and return that.
You can create a class which hold this 3 string and return that class, like ...
class String3 {
private String res1;
private String res2;
private String res3;
public String3(String res1, String res2, String res3) {
super();
this.res1 = res1;
this.res2 = res2;
this.res3 = res3;
}
public String getRes1() {
return res1;
}
public String getRes2() {
return res2;
}
public String getRes3() {
return res3;
}
}
Then you can use your Custom class like this.
private String3 method(String test) {
String a = "A"+test;
String b = "B"+test;
String c = "C"+test;
// Need to return all these 3 string to main method.
return new String3(a, b, c);
}
You can use a library like vavr to return a tuple.
Tuple3<String, String, String> result = Tuple.of(A, B, C);
The best option is to re-evaluate your code to see how you should do that in java.
You are trying use a solution that is not idiomatic in java, you should try to see how to decompose your problem in a java idiomatic way, not trying to apply solution which are typical of other languages, in the long run it will pay off.
and it has to return 3 strings or may be at times 2 strings and one int
In Java you can use Object type to represent any object, for example:
public void foo(Object obj){
if(obj instanceof String){ // obj is a String
System.out.println("Hello, " + (String) obj);
}
else if(obj instanceof Integer) { // obj is an integer value
// Integer is an object analog of int, because int is a primitive type
int my_int = (Integer) obj; // but we can implicitly convert Integer to int
System.out.println("I doubled your integer: " + my_int * 2);
}
}
// somewhere
foo("Steve"); // Hello, Steve
foo(2); // I doubled your integer: 4
So in your case you can return List of Objects:
private static List<Object> cusmethod(String test)
{
List<String> list = new ArrayList<>();
if(test.equals("return 3 strings")){
list.add("A" + test);
list.add("B" + test);
list.add("C" + test);
}
else if(test.equals("return 2 strings and an int")){
list.add("A" + test);
list.add("B" + test);
list.add(12345);
}
return list;
}
public static void main(String[] args) {
List <Object> ls = cusmethod("string1");
String s = (String) ls.get(0); //get string A
int x = (Integer) ls.get(2);
}

How to return an array that is called upon by another class?

So I asked a question previously about returning arrays in Java, to which I got an answer, and now my code is updated with a getter, however I keep getting something along the lines of:
Phone#b08deb
as an output, which is not what I want, and if I were to do something like:
return arr[1];
It tells me that Phone cannot be converted to Phone[], and I'm incredibly lost as to how to get simply the number "00000" to be spit out by the compiler from the array (as I do understand that I don't need to initialize the array because it defaults to 0)
Link to question:
How do I return an array to another class in Java?
Updated code:
class TheDriverClass
{
public static void main(String[] args)
{
Phone p = new Phone(5);
System.out.println(p);
// Here it's supposed to return the values of an array with size 5,
//so it should print out 00000
}
}
Next I have the class Phone:
class Phone
{
private Phone[] arr; //I'm supposed to keep the array private
public Phone(int theLength){
arr = new Phone[size];
}
public Phone[] getPhone(){
return arr;
}
}
When you System.out.println() an array it basically prints out the array pointer.
you need something like Arrays.toString(array) it will call the toString on each element and print out something that is human readable.
Also to have a Phone that you can read. You will need to override the toString() on it as well.
class Phone
{
private int[] numbers; //I'm supposed to keep the array private
public Phone(int theLength){
numbers = new int[theLength];
}
public int[] getPhone(){
return numbers;
}
#Override
public String toString() {
return Arrays.toString(numbers);// also can use return Arrays.toString(numbers).replaceAll(",|\\[|\\]| ", ""); to clean up the , and []s
}
}
public class HelloWorld {
public static void main(String[] args) {
Phone p = new Phone(5);
System.out.println(p.getPhone());
}
}
class Phone {
private int[] arr;
public Phone(int size) {
this.arr = new int[size];
}
/* convert array to string */
public String getPhone() {
return Arrays.toString(arr);
}
}
If you would like to get the exact output as "00000" format, then you need to use StringBuilder
In the Phone class, the Phone[] arr will default to null, hence using int[] will default values to 0
If you don't want to make any changes in Phone class then inherit Phone class in CustomPhone class and override toString. this will work when Phone class is not final. I guess the following code may solve your problem.
class PhoneCustom extends Phone{
public PhoneCustom(int theLength) {
super(theLength);
}
#Override
public String toString() {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < super.getPhone().length; i++) {
if(super.getPhone()[i] == null) {
sb.append(0);
}else {
sb.append(super.getPhone()[i]);
}
}
return sb.toString();
}
}
Also, modify toString according to your requirement in else part.
If you have flexiblity to modify you phone class then override the toString method in phone class.
class Phone
{
private Phone[] arr; //I'm supposed to keep the array private
public Phone(int theLength){
arr = new Phone[theLength];
}
public Phone[] getPhone(){
return arr;
}
#Override
public String toString() {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
sb.append(0);
}else {
sb.append(arr[i]);
}
}
return sb.toString();
}
}

How do I implement the toString() method for an ArrayStack?

I want to display a list of orders of type ArrayQueue <Order>
The class Order has an ArrayStack<String> as one of its attributes. I overrode the toString() method in the class Order, but how do I override it in the ArrayStack class? Because this is the output I get when I display:
OrderNumber Name Date ArrayStack#481adc30
What would I have to do to display the Strings in ArrayStack correctly? Do I make changes to class ArrayStack or change something in my Display method?
This is my Display method:
public void display(){
if (!isEmpty())
for (int i = 0; i < numberOfEntries; i++) {
System.out.println(queue[(frontIndex + i) % queue.length]);
}
else System.out.println("You don't have any orders");
}
ArrayStack Class:
public class ArrayStack < T > implements StackInterface < T >
{
private T [] stack; // array of stack entries
private int topIndex; // index of top entry
private static final int DEFAULT_INITIAL_CAPACITY = 50;
public ArrayStack ()
{
this (DEFAULT_INITIAL_CAPACITY);
} // end default constructor
public ArrayStack (int initialCapacity)
{
// the cast is safe because the new array contains null entries
# SuppressWarnings ("unchecked")
T [] tempStack = (T []) new Object [initialCapacity];
stack = tempStack;
topIndex = -1;
} // end constructor
/* Implementations of the stack operations */
Order Class:
import java.util.Date;
public class Order {
int orderNumber;
String customerName;
Date date;
StackInterface <String> items;
Order( int number, String name, Date datum, StackInterface<String> item){
orderNumber = number;
customerName= name;
date= datum;
items = item;
}
/Overriding toString() to Display a list of Orders as one String line.
public String toString(){
return orderNumber + " " + customerName + " " + date + " " + items;
}
You can override toString() method in ArrayStack as shown here. This will solve your problem.
public String toString() {
String result = "";
for (int scan = 0; scan < top; scan++)
result = result + stack[scan].toString() + "\n";
return result;
}
May be you should do this:
System.out.println(Arrays.toString(queue.toArray()));
Use this:
System.out.println(Arrays.toString(queue));

How to find the second largest element in an array of objects

I need to know the way to find the second largest element among an array of objects. for eg.
if there is an array of objects of a Book class with attributes like book name, price, in stock quantity
Book[] b=new Book[];
b[0]=new Book("x",200,50);
b[1]=new Book("y",100,44);
b[2]=new Book("z",500,29);
How can we list the book with second largest price along with other attributes like name and in stock quantity
Make a List of Books from it, sort it using Collections.sort and take the element on index 1.
List<Book> booklist = new ArrayList<Book>(Arrays.asList(b));
Collections.sort(booklist, new Comparator<Book>() {
#Override
public int compare(Book o1, Book o2) {
return o2.getPrice() - o1.getPrice();
}
});
if (booklist.size() > 1) {
System.out.println(booklist.get(1));
}
You can loop through this Array to find the largest and with this the second largest Element of the Array. Because the Elements are Objects you have to get the Value that you want to compare from the element with a getter or the variable is public in the objects.
public int getSecondLargest(Object[] obj){
int length = obj.length;
int largest = 0;
int secondLargest = 0;
for(int i = 0; i<length; i++){
if(obj[largest].getValue() <= obj[i].getValue()){
secondLargest = largest;
largst = i;
}
}
return secondLargest;
}
I think you should implements Interface Comparable.
and then use Collections.sort();
Implements a Comparator And sort your array, then pick second element.
class BookPriceComparator implements Comparator<Book> {
#Override
public int compare(Book a, Book b) {
return a.getPrice() - b.getPrice();
}
}
Arrays.sort(bookArr, new BookPriceComparator ());
import java.util.*;
//here you can make changes or you can create your own new class
//to sort book according to pages
class sortPrice implements Comparator<Test> {
public int compare(Test i1, Test i2) {
Integer x = i1.getPrice(), y = i2.getPrice();
return y.compareTo(x); // <--- changed
}
}
// in your case Test class could be Book class
public class Test {
/**
* #param args
*/
int price , page ;
String name;
Test(String n , int p ,int pg){
name=n;
price=p;
page=pg;
}
public String toString(){
return name+" "+price +" "+page ;
}
public String getName(){
return name;
}
public int getPage(){
return page;
}
public int getPrice(){
return price;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test[] b=new Test[3];
b[0]=new Test("x",200,50);
b[1]=new Test("y",100,44);
b[2]=new Test("z",500,29);
ArrayList<Test> a = new ArrayList<>();
for(int i=0;i<3;i++){
a.add(b[i]);
}
sortPrice s= new sortPrice(); // required to pass as argument to tell
//based on which sorting order you want to sort
Collections.sort(a,s ); //here we are sorting Test(Book) based on price.
System.out.println(a.get(1)); // printing arrayList //<----- changed
}
}

Access object.variable in an array of objects

I need help with this piece of code.
public class ParkingLot {
static int MAX = 5;
static Car[] Slot = new Car[MAX];
public static void main(String[] args) {
Slot[0] = new Car("1234", "White");
Slot[1] = new Car("5678", "Black");
}
public static void Allot() {
for (int i = 0; i <= Slot.length; i++) {
System.out.println(Slot.getNo);
}
}
I am storing a Car Object in Slot. I wish to print/access the No and Colour of the car stored in slot. How do I go about doing that?
Well, if car has a public property, or a public getter method (this is preferable - getNumber() and getColour()), you can call them while iterating the array with the for-each loop:
for (Car car : slot) {
System.out.println(car.getColour());
}
Note that I've lowercased slot - variable names in Java should be lowercase. I'd also advise for naming the array with plural name - i.e. slots.
Note also that the way of iteration provided by others is possible, but not recommended for the basic case of iterating the whole array. Effective Java (Bloch) recommends using the foreach loop whenever possible.
Using [] notation:
public static void Allot() {
Car car;
for (int i = 0; i <= Slot.length; i++) {
// Get the car at this position in the array
car = Slot[i];
// Make sure it isn't null, since the array may not have
// a full set of cars
if (car != null) {
// Use the car reference
System.out.println(car.getNo());
}
}
}
(I assumed by the name that getNo was a method, not a property.)
E.g., Slot[0] gives you the first Car, from which you can access Car's properties and methods, so Slot[i] gives you the car at the ith position. (In the above I used a temporary variable to store the car, but you can use Slot[i].getNo() directly, it doesn't matter. I just didn't want to repeat the array lookup, even through HotSpot [the Sun JVM] will optimize it out even if I do.)
Sorry for being so late. I noticed something missing in the above answers, so here is the complete solution for the problem stated.
Here is the ParkingLot class with a call to Allot() method.
public class ParkingLot {
static int MAX = 5;
static Car[] Slot = new Car[MAX];
public static void main(String[] args) {
Slot[0] = new Car("1234", "White");
Slot[1] = new Car("5678", "Black");
Allot();
}
public static void Allot() {
for (int i = 0; i < Slot.length; i++) {
if (Slot[i] != null) {
System.out.println(Slot[i].getNo()+" , "+Slot[i].getColor());
}
}
}
}
And the Car class with the getNo() and getColor() methods.
public class Car {
private String Number;
private String Color;
Car (String Number, String Color){
this.Number = Number;
this.Color = Color;
}
public String getNo(){
return Number;
}
public String getColor(){
return Color;
}
}
class Car{
String number;
String color;
public Car(String number, String color) {
this.number = number;
this.color = color;
}
#Override
public String toString() {
return "Car{" +
"number='" + number + '\'' +
", color='" + color + '\'' +
'}';
}
}
class Test{
static int MAX = 5;
static Car[] Slot = new Car[MAX];
public static void main(String[] args) {
Slot[0] = new Car("1234", "White");
Slot[1] = new Car("5678", "Black");
for (Car car : Slot)
System.out.println(car);
}
}
you can create and access object array of objects simply like this
Object[] row={"xx","xcxcx"};
Object[] cotainer = {row,row,row};
for(int a=0;a<cotainer.length;a++){
Object[] obj = (Object[])cotainer[a];
}

Categories