I want to have a list of 100 students with attributes. How can I have such a list in java without using add.list() for 100 times?

arraylist of objects in java
java program for student mark list using array
arraylist java
java program for student details using arraylist
java list
java program for student information using class and object
java program for student database
collections in java

I tried the conventional way to create list and adding Details with Credentials class


import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;

public class New {

    public static void main(String[] args) {
        List<Credentials> stud = new ArrayList<>();

        Credentials c1 = new Credentials("Aditya", 1, 15);
        Credentials c2 = new Credentials("Ramesh", 2, 15);
        Credentials c3 = new Credentials("Suresh", 3, 15);
        Credentials c4 = new Credentials("Mahesh", 4, 15);
        Credentials c5 = new Credentials("Naresh", 5, 15);
        Credentials c6 = new Credentials("Sarvesh", 6, 15);
        Credentials c7 = new Credentials("Jayesh", 7, 15);
        Credentials c8 = new Credentials("Paresh", 8, 15);
        Credentials c9 = new Credentials("Nilesh", 9, 15);
        Credentials c10 = new Credentials("Yogesh", 10, 15);
        Credentials c11 = new Credentials("Mahi", 11, 15);
        Credentials c12 = new Credentials("Lonesh", 12, 15);
        Credentials c13 = new Credentials("Prakash", 13, 15);
        Credentials c14 = new Credentials("Akash", 14, 15);
        Credentials c15 = new Credentials("Surya", 15, 15);
        Credentials c16 = new Credentials("Dinesh", 16, 15);
        Credentials c17 = new Credentials("Saresh", 17, 15);


        Iterator<Credentials> iterator = stud.iterator();
        while (iterator.hasNext()) {

You could use :

List<Credentials> stud = Arrays.asList(new Credentials("Aditya", 1, 15), 
                                       new Credentials("Ramesh", 2, 15), 
                                       new Credentials("Suresh", 3, 15),

Do note that the list stud cannot be structurally modified i.e. you cannot add or remove any elements from it now.

ArrayList in java with example programs, Arraylist class implements List interface and it is based on an Array data For example: If we want to add the element at the end of the List then simply do it like this: Note: Since the index starts with 0, index 3 would represent fourth position not have given the index as 0 and new element as “Lucy” in the set() method, so  You will need to keep the list in your course class as an instance variable, and add a method in wich you can pass a student and inside the method all you have to is add to your list of students, you may even do some validation if you want. If you have more doubts first search for a solution before asking questions that can easily be found.

Read the list from a file of some sort (simple delimited text, JSON, ...).

I want to write simple java program without using list.add so many times

Fundamentally, you're going to have 100 very similar lines if you're going to embed this in the code. What those 100 very similar lines are is largely up to you, but there's no reason for all those variables (c1, c2, etc.).


public static void main(String[] args) {
    List<Credentials> stud = new ArrayList<>();

    stud.add(new Credentials("Aditya", 1, 15));
    stud.add(new Credentials("Ramesh", 2, 15));
    stud.add(new Credentials("Suresh", 3, 15));
    stud.add(new Credentials("Mahesh", 4, 15));
    stud.add(new Credentials("Naresh", 5, 15));
    // ...

Possibly even put that in a reusable function:

private static void addStudent(stud, name, x, y) {
    stud.add(new Credentials(name, x, y));
public static void main(String[] args) {
    List<Credentials> stud = new ArrayList<>();

    addStudent(stud, "Aditya", 1, 15);
    addStudent(stud, "Ramesh", 2, 15);
    addStudent(stud, "Suresh", 3, 15);
    addStudent(stud, "Mahesh", 4, 15);
    addStudent(stud, "Naresh", 5, 15);
    // ...

If the list of students is fixed, don't use an ArrayList at all, use an array:

public static void main(String[] args) {
    Credentials[] stud = new Credentials[] {
        new Credentials("Aditya", 1, 15),
        new Credentials("Ramesh", 2, 15),
        new Credentials("Suresh", 3, 15),
        new Credentials("Mahesh", 4, 15),
        new Credentials("Naresh", 5, 15),
        // ...

Java programming exercises: Accepts students name, id, and marks , Java programming exercises and solution: Write a Java program students name, id, and marks and display the highest score and the The score is an integer between 0 and 100. class Student { String name; String stu_id; int score​; public Student() There was a problem connecting to the server. Pre-requisite: Linked List Data Structure Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at the contiguous location, the elements are linked using pointers as shown below.

Here is how I would write the same code that you wrote:

public class New {

    public static void main(String[] args) {
        List<Credentials> stud = new ArrayList<>();

        // The only part that requires writing individual information is the names
        // because each is different and there is no "rule"

        String[] names = { "Aditya",

        // This loop does both the creation of the credetntials and adding them
        // to the list. The same thing could be done with Java 8 streams but
        // I use the conventional method for simplicity.

        for ( int i = 0; i < names.length; i++ ) {
            stud.add( new Credentials( names[i], i+1, 15 ) );

        // This can actually be replaced with an enhanced for loop.

        Iterator<Credentials> iterator = stud.iterator();
        while (iterator.hasNext()) {

In the real world, you may want to read the names from a file rather than write them in the source. But anyway, when you use an array instead of separate variables, you can do repetitive tasks using a loop and the index of the array.

For each of your names, what you do is create a Credentials object where the second parameter is a sequential number, and the last parameter is 15.

The indices of the array start from 0. The sequential numbers are from 1. This means that just using i+1 gives you exactly the sequential number that you need.

So everything was folded into these three lines:

        for ( int i = 0; i < names.length; i++ ) {
            stud.add( new Credentials( names[i], i+1, 15 ) );

Now you can add 100 names to your initial array of names, and you don't have to change anything.

Randomly select items from a List in Java, The basic idea for pick an item from list is, First generate a number which you can always use static method Math.random()(random() method generate an we want to select after that we select items one by one and add a new list and return it. select many times because we are not remove selected elements so list size​  How to iterate through Java List? This tutorial demonstrates the use of ArrayList, Iterator and a List. There are 7 ways you can iterate through List.

I think this task is not how to declare an ArrayList, but how to store user credentials. There're several important parts here:

  1. Credentials should not be save directly in code, because they should be midifiable without code recompilation and rebuild. It's general practic to store it in some external resourse: database, vault, LDAP, text file in resource.
  2. Storage format could be changed, so reading and saving parts should be splitted in the code. In case of changing storage type, it should be pretty easy to replace reading strategy in the code.
  3. Credentials should be loaded at the start of the application and be available at constant time for reading. Therefore, it is common practice to save credentials (at runtime) in separate service and work with each user by it's id (not name, because name could be changed someday).

To be clear, this is my solution.

Credential class should contain immutable unique id (or much better is UUID). Application should work with given credential only by this id.

public final class Credentials {

    private final int id;
    private final String name;
    private final int mask;

    public Credentials(int id, String name, int mask) {
        this.name = name;
        this.id = id;
        this.mask = mask;

Example of external credetials.csv:


PermissionService is a singleton and contains all loglic for check permissions. In this example it contains a HashMap where id is a key and required credentials could be available at constant time.

This service contains one method to read external file (with know format) to read current credentials at startup.

public final class PermissionService {

    private static final Pattern COMMA = Pattern.compile("\\s*,\\s*");
    private static final int ID = 0;
    private static final int NAME = 1;
    private static final int MASK = 2;

    private final Map<Integer, Credentials> map = new HashMap<>();

    public void loadPermissions(Path path) throws IOException {

             .map(parts -> new Credentials(Integer.parseInt(parts[ID]), parts[NAME], Integer.parseInt(parts[MASK])))
             .forEach(credentials -> map.put(credentials.getId(), credentials));

That's all in general. Yes, you could change the external storage type, the way how to ready this file or update it, or format of the file. But general principle will be the same.


If you do not want to use external resource, you can hold this data directly in the PermissionService, and it does not matter why exactly you init a list. Main case is that this should be incapsulated in separate service and be easy to update in the future if required.

Java sort arraylist of objects, If you have overridden equals() method in your If two objects are equal using equals() method then If we have generic list with different object, how can we sort it Can we sort this based on price? if so please help method internally calls compareTo() method or not. Prerequisite – ArrayList in Java ArrayList in Java (equivalent to vector in C++) having dynamic size. It can be shrinked or expanded based on size. ArrayList is a part of collection framework and is present in java.util package. An ArrayList: ArrayList <E> list = new ArrayList <> (); E here represents an object datatype e.g. Integer.

Creating and Using Arrays, that creates the array, puts some values in it, and displays the values. public class Like declarations for variables of other types, an array declaration has two The sample program uses int[] , so the array called anArray will be used to hold integer data. ArrayDemo.java:4: Variable anArray may not have been initialized. The rewards list can be anything they want it to be—from free computer time to chips, on the small end of the scale, to a pizza party or field trip as larger rewards. Step 4 Ask a student to create a large poster listing the top 10 expectations to hang in the classroom.

Generic Array Lists | Understanding Inheritance in Java, To specify the type of the element objects that the array list holds, you append a class name enclosed in angle brackets, such as ArrayList<Employee>. Then, the first 100 calls to add do not involve any costly reallocation. Before Java SE 5.0, there were no generic classes, and the get method of the raw  Teaching comes quite naturally to some who are born leaders, yet others have to work hard to achieve ‘great teacher’ status. Whichever category you fall into, if you want to help young students and make a lasting impression, these top skills and qualities can place you at a great advantage.

Python Programming with the Java Class Libraries: A Tutorial for , The first argument in a method usually refers to an instance of a class, but not here. Instead Again, the syntax is like that for accessing variables in a module. Then we accessed the values in the member list called toc. To do this with what we've learned so far, we'd have to redefine chapter 20 times. class chapter1​:  However if the ArrayList is of custom object type then in such case you have two options for sorting- comparable and comparator interfaces. Before going through the example of them, let’s see what’s the output when we try to sort arraylist of Objects without implementing any of these interfaces.

  • Have you thought about creating a JSON and reading it?
  • Let's start with something simple, without external resources: Never use variables with numbers like c1, c2, c3 etc. - If you find yourself doing that, use an array instead. Arrays can be initialized in bulk and you can loop over them to manipulate the data.
  • I want to write simple java program without using list.add so many times. that's all