打印数组列表

我有一个包含 Address 对象的 ArrayList。

如何打印这个 ArrayList 的值,这意味着我要打印 Array 的内容,在本例中是数字。

我只能让它用这段代码打印出数组的实际内存地址:

for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i));
}
859357 次浏览

Are you saying that ArrayList is storing addresses of arrays because that is what is returning from the toString call, or because that's actually what you're storing?

If you have an ArrayList of arrays (e.g.

int[] arr = {1, 2, 3};
houseAddress.add(arr);

Then to print the array values you need to call Arrays.deepToString:

for (int i = 0; i < houseAddress.size(); i++) {
System.out.println(Arrays.deepToString(houseAddress.get(i)));
}

since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object

in your Address class override the toString() method like this

public class Address {


int addressNo ;
....
....
...


protected String toString(){
return Integer.toString(addressNo);
}

now when you call

houseAddress.get(i)  in the `System.out.print()` method like this

System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called

Add toString() method to your address class then do

System.out.println(Arrays.toString(houseAddress));

Put houseAddress.get(i) inside the brackets and call .toString() function: i.e Please see below

for(int i = 0; i < houseAddress.size(); i++) {
System.out.print((houseAddress.get(i)).toString());
}
public void printList(ArrayList<Address> list){
for(Address elem : list){
System.out.println(elem+"  ");
}
}

You can simply give it as:

System.out.println("Address:" +houseAddress);

Your output will look like [address1, address2, address3]

This is because the class ArrayList or its superclass would have a toString() function overridden.

Hope this helps.

I am not sure if I understood the notion of addresses (I am assuming houseAddress here), but if you are looking for way a to print the ArrayList, here you go:

System.out.println(houseAddress.toString().replaceAll("\\[\\]", ""));

list.toString() is good enough.

The interface List does not define a contract for toString(), but the AbstractCollection base class provides a useful implementation that ArrayList inherits.

This helped to me:

System.out.println(Arrays.toString(codeLangArray.toArray()));

Since Java 8, you can use forEach() method from Iterable interface.
It's a default method. As an argument, it takes an object of class, which implements functional interface Consumer. You can implement Consumer locally in three ways:

With annonymous class:

houseAddress.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});

lambda expression:

houseAddress.forEach(s -> System.out.println(s));

or by using method reference:

houseAddress.forEach(System.out::print);

This way of printing works for all implementations of Iterable interface.
All of them, gives you the way of defining how the elements will be printed, whereas toString() enforces printing list in one format.

From what I understand you are trying to print an ArrayList of arrays and one way to display that would be

System.out.println(Arrays.deepToString(list.toArray()));

You can use an Iterator. It is the most simple and least controvercial thing to do over here. Say houseAddress has values of data type String

Iterator<String> iterator = houseAddress.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}

Note : You can even use an enhanced for loop for this as mentioned by me in another answer

You can even use an enhanced for loop or an iterator like:

for (String name : houseAddress) {
System.out.println(name);
}

You can change it to whatever data type houseAddress is and it avoids unnecessary conversions

assium that you have a numbers list like that

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

if you print the list

//method 1
// Conventional way of printing arraylist
for (int number : numbers) {
System.out.print(number);
}


//method 2
// Lambda Expression to print arraylist
numbers.forEach((Integer value) -> System.out.print(value));


//method 3
// Lambda Expression to print arraylist
numbers.forEach(value -> System.out.print(value));




//method 4
// Lambda Expression (method reference) to print arraylist
numbers.forEach(System.out::print);

if you make the @Override public String toString() as comments, you will have the same results as you did. But if you implement your toString() method, it will work.

public class PrintingComplexArrayList {

public static void main(String[] args) {
List houseAddress = new ArrayList();
insertAddress(houseAddress);
printMe1(houseAddress);
printMe2(houseAddress);
}


private static void insertAddress(List address)
{
address.add(new Address(1));
address.add(new Address(2));
address.add(new Address(3));
address.add(new Address(4));
}
private static void printMe1(List address)
{
for (int i=0; i<address.size(); i++)
System.out.println(address.get(i));
}


private static void printMe2(List address)
{
System.out.println(address);
}

}

class Address{ private int addr; public Address(int i) { addr = i; }

@Override public String toString()
{
Integer iAddr = new Integer (addr);
return iAddr.toString();
}

}

Make sure you have a getter in House address class and then use:

for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i)**.getAddress()**);
}

you can use print format if you just want to print the element on the console.

for(int i = 0; i < houseAddress.size(); i++) {
System.out.printf("%s", houseAddress.get(i));
}
 public static void main(String[] args) {
List<Moyen> list = new ArrayList<Moyen>();
Moyen m1 = new Moyen();
m1.setCodification("c1");
m1.setCapacityManager("Avinash");
Moyen m2 = new Moyen();
m2.setCodification("c1");
m2.setCapacityManager("Avinash");
Moyen m3 = new Moyen();
m3.setCodification("c1");
m3.setCapacityManager("Avinash");


list.add(m1);
list.add(m2);
list.add(m3);
System.out.println(Arrays.toString(list.toArray()));
}

Assuming that houseAddress.get(i) is an ArrayList you can add toString() after the ArrayList :

for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i).toString());
}

A general example:

ArrayList<Double> a = new ArrayList();
a.add(2.);
a.add(32.);
System.out.println(a.toString());
// output
// [2.0, 32.0]

This is a simple code of add the value in ArrayList and print the ArrayList Value

public class Samim {


public static void main(String args[]) {
// Declare list
List<String> list = new ArrayList<>();


// Add value in list
list.add("First Value ArrayPosition=0");
list.add("Second Value ArrayPosition=1");
list.add("Third Value ArrayPosition=2");
list.add("Fourth Value ArrayPosition=3");
list.add("Fifth Value ArrayPosition=4");
list.add("Sixth Value ArrayPosition=5");
list.add("Seventh Value ArrayPosition=6");


String[] objects1 = list.toArray(new String[0]);


// Print Position Value
System.err.println(objects1[2]);


// Print All Value
for (String val : objects1) {
System.out.println(val);
}
}
}

Simplest way to print an ArrayList is by using toString

List<String> a=new ArrayList<>();
a.add("111");
a.add("112");
a.add("113");
System.out.println(a.toString());

Output

[111, 112, 113]

JSON

An alternative Solution could be converting your list in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString(). Additionaly it works for any other Object or Collection on the fly.

Example using Google's Gson:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


...
public static void printJsonString(Object o) {
GsonBuilder gsonBuilder = new GsonBuilder();
/*
* Some options for GsonBuilder like setting dateformat or pretty printing
*/
Gson gson = gsonBuilder.create();
String json= gson.toJson(o);
System.out.println(json);
}
  1. Add toString() method to your class
  2. houseAddress.forEach(System.out::println);

Consider using an "Enhanced for loop" I had to do this solution for a scenario in which the arrayList was coming from a class object

changing the String datatype to the appropriate datatype or class object as desired.

ArrayList<String> teamRoster = new ArrayList<String>();


// Adding player names
teamRoster.add("Mike");
teamRoster.add("Scottie");
teamRoster.add("Toni");


System.out.println("Current roster: ");


for (String playerName : teamRoster) {
System.out.println(playerName);
// if using an object datatype, you may need to use a solution such as playerName.getPlayer()
}