Contoh ArrayList<Mahasiswa>

Run Settings
LanguageJava
Language Version
Run Command
import java.util.ArrayList; import java.util.List; public class ContohArrayList2 { public static void main(String[] args) { ArrayList<Mahasiswa> mahasiswa = new ArrayList<>(); // menambah elemen // 1. buat objeknya dulu Mahasiswa mhs = new Mahasiswa(); mhs.setNim("112233"); mhs.setNama("Adi Putra"); Mahasiswa mhs2 = new Mahasiswa(); mhs2.setNim("223344"); mhs2.setNama("Budi Santoso"); // 2. memasukkan objek ke arraylist mahasiswa.addAll(List.of(mhs, mhs2)); // mengambil elemen (mhs2) Mahasiswa objek = mahasiswa.get(0); System.out.println(objek.getNim()); System.out.println(objek.getNama()); System.out.println(); Mahasiswa objek2 = mahasiswa.get(1); System.out.println(objek2.getNim()); System.out.println(objek2.getNama()); System.out.println("----------"); for (int i=0; i<mahasiswa.size(); i++) { Mahasiswa m = mahasiswa.get(i); System.out.println(m.getNim()); } // ubah elemen Mahasiswa mhsBaru = new Mahasiswa(); mhsBaru.setNim("555555"); mhsBaru.setNama("Cindy"); mahasiswa.set(1, mhsBaru); System.out.println("----------"); for (int i=0; i<mahasiswa.size(); i++) { Mahasiswa m = mahasiswa.get(i); System.out.println(m.getNama()); } // hapus elemen mahasiswa.remove(1); System.out.println("----------"); for (int i=0; i<mahasiswa.size(); i++) { Mahasiswa m = mahasiswa.get(i); System.out.println(m.getNama()); } } } class Mahasiswa { private String nim, nama; public String getNim() { return nim; } public void setNim(String nim) { this.nim = nim; } public String getNama() { return nama; } public void setNama(String nama) { this.nama = nama; } }
Editor Settings
Theme
Key bindings
Full width
Lines