Contoh ArrayList (Objek)

Run Settings
LanguageJava
Language Version
Run Command
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { ArrayList<Mahasiswa> list = new ArrayList<>(); Scanner input = new Scanner(System.in); System.out.print("Masukkan jumlah mahasiswa: "); String jumlah = input.nextLine(); // 3 // masukkan data sebanyak "jumlah" for (int i=0; i<Integer.parseInt(jumlah); i++) { Mahasiswa mhs = new Mahasiswa(); System.out.print("Masukkan nama: "); mhs.setNama(input.nextLine()); System.out.print("Alamat: "); mhs.setAlamat(input.nextLine()); System.out.print("Usia: "); String usia = input.nextLine(); mhs.setUsia(Integer.parseInt(usia)); list.add(mhs); // tambahkan objek ke dalam list } for (int i=0; i<Integer.parseInt(jumlah); i++) { // atau gunakan for(int i=0; i<list.size(); i++) System.out.println(list.get(i).getNama()); System.out.println(list.get(i).getUsia()); System.out.println(list.get(i).getAlamat()); System.out.println(); } // atau gunakan // for(Mahasiswa mhs: list) { // System.out.println(mhs.getNama()); // System.out.println(mhs.getUsia()); // System.out.println(mhs.getAlamat()); // System.out.println(); // } } } class Mahasiswa { private String nama; private int usia; private String alamat; public void setNama(String nama) { this.nama = nama; } public void setUsia(int usia) { this.usia = usia; } public void setAlamat(String alamat) { this.alamat = alamat; } public String getNama() { return nama; } public int getUsia() { return usia; } public String getAlamat() { return alamat; } }
Editor Settings
Theme
Key bindings
Full width
Lines