Java AbstractCollection toString()

PreviousNext

Java AbstractCollection toString() Returns a string representation of this collection.

Introduction

Returns a string representation of this collection.

The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]").

Adjacent elements are separated by the characters (", ") (comma and space).

Elements are converted to strings as by String#valueOf(Object).

Syntax

The method toString() from AbstractCollection is declared as:

public String toString()

Return

The method toString() returns a string representation of this collection

Example

The following code shows how to use Java AbstractCollection toString()

Example 1

// Java program to demonstrate
// Abstract Collection toString() method

import java.util.*;

public class Main {
    public static void main(String args[]) {
        // Creating an Empty AbstractCollection
        AbstractCollection<Integer> abs = new PriorityQueue<Integer>();

        // Use add() method
        // to add elements to the Collection
        abs.add(10);//   w w   w  . d    em  o    2  s . c    o m 
        abs.add(20);
        abs.add(30);
        abs.add(40);

        // Using toString() method
        System.out.println(abs.toString());
    }
}

Result

Example 2

// Java program to demonstrate
// Abstract Collection toString() method

import java.util.*;

public class Main {
    public static void main(String args[]) {
        // Creating an Empty AbstractCollection
        AbstractCollection<String> abs = new PriorityQueue<String>();

        // Use add() method
        // to add elements to the Collection
        abs.add("Welcome");
        abs.add("To");
        abs.add("demo2s.com");
        abs.add("For");
        abs.add("demo2s.com");

        // Using toString() method
        System.out.println(abs.toString());
    }//    w w   w.    d e m    o 2 s    .  co   m 
}

Result

PreviousNext

Related