5. Arrays & Collections Intro
Bu bo‘limda Java’da bir nechta qiymatlarni saqlashni o‘rganamiz.
Oldingi mavzularda bitta qiymat saqladik:
String name = "Ali";
int age = 25;
Lekin real dasturda ko‘pincha bitta emas, ko‘p qiymatlar bilan ishlaymiz:
10 ta user
100 ta product
1000 ta order
telefon raqamlar ro‘yxati
baholar ro‘yxati
Shuning uchun Java’da array va collection ishlatiladi.
Roadmapdagi Beginner bo‘limida bu qism quyidagilarni o‘z ichiga oladi: 1D & 2D arrays, ArrayList basics, HashMap basics, iterating collections.
5.1. Array nima?
Array - bir xil turdagi bir nechta qiymatlarni bitta joyda saqlaydigan tuzilma.
Masalan, 5 ta son saqlash:
int[] numbers = {10, 20, 30, 40, 50};
Bu yerda:
int[] → int array
numbers → array nomi
{...} → qiymatlar
Oddiy qilib:
numbers degan qutida 5 ta int qiymat turibdi.
5.2. Array index
Array elementlari index orqali olinadi.
Muhim qoida:
Java’da index 0 dan boshlanadi.
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);
Natija:
10
20
30
Array ko‘rinishi:
index: 0 1 2 3 4
value: 10 20 30 40 50
Demak:
numbers[0] // 10
numbers[1] // 20
numbers[4] // 50
5.3. Array elementini o‘zgartirish
Array ichidagi qiymatni index orqali o‘zgartirish mumkin:
int[] numbers = {10, 20, 30};
numbers[1] = 99;
System.out.println(numbers[1]);
Natija:
99
Oldin:
numbers[1] = 20
Keyin:
numbers[1] = 99
5.4. Array uzunligi
Array uzunligini olish uchun .length ishlatiladi.
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers.length);
Natija:
4
E’tibor ber:
numbers.length
Bu method emas, field. Shuning uchun qavs yozilmaydi.
Noto‘g‘ri:
numbers.length();
To‘g‘ri:
numbers.length;
5.5. Array yaratishning boshqa usuli
Agar qiymatlarni keyinroq beradigan bo‘lsak:
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
Bu yerda:
new int[3]
3 ta int saqlaydigan array yaratadi.
Default qiymatlar:
int → 0
double → 0.0
boolean → false
String → null
object → null
Misol:
int[] numbers = new int[3];
System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);
Natija:
0
0
0
5.6. Array chegarasidan chiqib ketish
Array’da mavjud bo‘lmagan indexga murojaat qilsang, xato bo‘ladi.
int[] numbers = {10, 20, 30};
System.out.println(numbers[3]);
Bu xato:
ArrayIndexOutOfBoundsException
Nega?
numbers length = 3
indexlar: 0, 1, 2
numbers[3] mavjud emas
Beginnerlar ko‘p qiladigan xato:
int[] numbers = {10, 20, 30};
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]);
}
Bu noto‘g‘ri. Chunki oxirida i = 3 bo‘ladi.
To‘g‘ri:
int[] numbers = {10, 20, 30};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Muhim qoida:
i < array.length
<= emas.
5.7. Array bo‘ylab yurish: for
String[] names = {"Ali", "Vali", "Sami"};
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
Natija:
Ali
Vali
Sami
Bu usul index kerak bo‘lganda yaxshi.
Masalan:
String[] names = {"Ali", "Vali", "Sami"};
for (int i = 0; i < names.length; i++) {
System.out.println(i + ": " + names[i]);
}
Natija:
0: Ali
1: Vali
2: Sami
5.8. Array bo‘ylab yurish: for-each
Agar index kerak bo‘lmasa, for-each osonroq.
String[] names = {"Ali", "Vali", "Sami"};
for (String name : names) {
System.out.println(name);
}
Natija:
Ali
Vali
Sami
Tushunish:
names ichidagi har bir elementni olib, name degan variable’ga ber.
5.9. for va for-each farqi
Holat | Tavsiya |
|---|---|
Index kerak bo‘lsa |
|
Faqat elementlarni o‘qish kerak bo‘lsa |
|
Elementni index orqali o‘zgartirish kerak bo‘lsa |
|
Kod o‘qilishi oson bo‘lishi kerak bo‘lsa |
|
Misol: elementni o‘zgartirish kerak bo‘lsa:
int[] numbers = {1, 2, 3};
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] * 2;
}
Natija array ichida:
2, 4, 6
5.10. 2D array nima?
2D array - array ichida array. Jadvalga o‘xshaydi.
Masalan:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Ko‘rinishi:
row 0: 1 2 3
row 1: 4 5 6
row 2: 7 8 9
Element olish:
System.out.println(matrix[0][0]);
System.out.println(matrix[1][2]);
System.out.println(matrix[2][1]);
Natija:
1
6
8
Tushunish:
matrix[row][column]
5.11. 2D array bo‘ylab yurish
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
Natija:
1 2 3
4 5 6
7 8 9
Bu yerda:
matrix.length
row soni.
matrix[row].length
shu row ichidagi column soni.
5.12. Array muammosi
Array yaxshi, lekin bitta katta cheklovi bor:
Array uzunligi yaratilgandan keyin o‘zgarmaydi.
Masalan:
int[] numbers = new int[3];
Bu array faqat 3 ta element saqlaydi. Keyin 4-elementni qo‘shib bo‘lmaydi.
numbers[3] = 40; // xato
Shuning uchun real loyihalarda ko‘pincha ArrayList ishlatiladi.
5.13. ArrayList nima?
ArrayList - o‘lchami o‘zgaradigan ro‘yxat.
Array:
fixed size
ArrayList:
dynamic size
Ishlatish uchun import kerak:
import java.util.ArrayList;
Misol:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ali");
names.add("Vali");
names.add("Sami");
System.out.println(names);
}
}
Natija:
[Ali, Vali, Sami]
5.14. ArrayList generic type
ArrayList<String> names = new ArrayList<>();
Bu degani:
Bu ro‘yxatda faqat String saqlanadi.
Sonlar uchun:
ArrayList<Integer> numbers = new ArrayList<>();
E’tibor ber:
ArrayList<int> numbers = new ArrayList<>(); // xato
To‘g‘ri:
ArrayList<Integer> numbers = new ArrayList<>();
Nega?
Chunki collection’lar primitive type bilan emas, object type bilan ishlaydi.
Primitive | Wrapper class |
|---|---|
|
|
|
|
|
|
|
|
|
|
5.15. ArrayList asosiy methodlari
add()
Element qo‘shadi.
ArrayList<String> names = new ArrayList<>();
names.add("Ali");
names.add("Vali");
get()
Index bo‘yicha element oladi.
System.out.println(names.get(0));
Natija:
Ali
set()
Indexdagi elementni o‘zgartiradi.
names.set(1, "Sami");
remove()
Elementni o‘chiradi.
names.remove("Ali");
Yoki index bo‘yicha:
names.remove(0);
size()
Elementlar sonini qaytaradi.
System.out.println(names.size());
E’tibor ber:
array.length
arrayList.size()
Array’da length, ArrayList’da size().
contains()
Element bor-yo‘qligini tekshiradi.
boolean exists = names.contains("Ali");
System.out.println(exists);
5.16. ArrayList bilan to‘liq misol
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> users = new ArrayList<>();
users.add("Ali");
users.add("Vali");
users.add("Sami");
System.out.println("Users count: " + users.size());
System.out.println("First user: " + users.get(0));
users.set(1, "Hasan");
users.remove("Sami");
for (String user : users) {
System.out.println(user);
}
}
}
Natija:
Users count: 3
First user: Ali
Ali
Hasan
5.17. ArrayList bo‘ylab yurish
Index bilan:
ArrayList<String> names = new ArrayList<>();
names.add("Ali");
names.add("Vali");
names.add("Sami");
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
for-each bilan:
for (String name : names) {
System.out.println(name);
}
Ko‘p hollarda for-each o‘qilishi osonroq.
5.18. HashMap nima?
HashMap - key-value ko‘rinishida ma’lumot saqlaydi.
Ya’ni har bir qiymatning kaliti bo‘ladi.
Masalan:
phoneBook:
Ali → +998901111111
Vali → +998902222222
Sami → +998903333333
Java’da:
import java.util.HashMap;
HashMap<String, String> phoneBook = new HashMap<>();
phoneBook.put("Ali", "+998901111111");
phoneBook.put("Vali", "+998902222222");
phoneBook.put("Sami", "+998903333333");
Bu yerda:
HashMap<String, String>
Birinchi String - key type.
Ikkinchi String - value type.
key → name
value → phone number
5.19. HashMap asosiy methodlari
put()
Key-value qo‘shadi yoki mavjud key qiymatini yangilaydi.
phoneBook.put("Ali", "+998901111111");
Agar Ali oldin bor bo‘lsa, qiymati yangilanadi.
phoneBook.put("Ali", "+998909999999");
get()
Key bo‘yicha value oladi.
String phone = phoneBook.get("Ali");
System.out.println(phone);
Natija:
+998901111111
containsKey()
Key bor-yo‘qligini tekshiradi.
if (phoneBook.containsKey("Ali")) {
System.out.println("Ali bor");
}
remove()
Key bo‘yicha elementni o‘chiradi.
phoneBook.remove("Ali");
size()
Elementlar sonini qaytaradi.
System.out.println(phoneBook.size());
5.20. HashMap bilan to‘liq misol
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Ali", 90);
scores.put("Vali", 75);
scores.put("Sami", 88);
System.out.println("Ali score: " + scores.get("Ali"));
if (scores.containsKey("Vali")) {
System.out.println("Vali bor");
}
scores.put("Vali", 80);
scores.remove("Sami");
System.out.println(scores);
}
}
Natija:
Ali score: 90
Vali bor
{Vali=80, Ali=90}
HashMap’da tartib kafolatlanmaydi. Shuning uchun natija tartibi boshqacha chiqishi mumkin.
5.21. HashMap bo‘ylab yurish
Faqat key’lar bo‘yicha
for (String name : scores.keySet()) {
System.out.println(name);
}
Faqat value’lar bo‘yicha
for (Integer score : scores.values()) {
System.out.println(score);
}
Key va value birga
for (String name : scores.keySet()) {
Integer score = scores.get(name);
System.out.println(name + ": " + score);
}
Yaxshiroq usul:
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Agar var ishlatmasak:
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Bunda import kerak:
import java.util.Map;
5.22. Array, ArrayList, HashMap farqi
Tuzilma | Qachon ishlatiladi? | Misol |
|---|---|---|
| O‘lcham oldindan aniq bo‘lsa | 7 kunlik hafta |
| Ro‘yxat o‘zgarib tursa | userlar ro‘yxati |
| Key orqali tez topish kerak bo‘lsa | username → userId |
Oddiy misol:
Array → 5 ta baho
ArrayList → buyurtmalar ro‘yxati
HashMap → productId bo‘yicha product topish
5.23. Real hayotga yaqin misol
Tasavvur qil: mini shop dasturi bor.
Mahsulot nomlari ro‘yxati:
ArrayList<String> products = new ArrayList<>();
products.add("Laptop");
products.add("Mouse");
products.add("Keyboard");
Mahsulot narxlari:
HashMap<String, Double> prices = new HashMap<>();
prices.put("Laptop", 1000.0);
prices.put("Mouse", 20.0);
prices.put("Keyboard", 50.0);
Chiqarish:
for (String product : products) {
Double price = prices.get(product);
System.out.println(product + " = $" + price);
}
Natija:
Laptop = $1000.0
Mouse = $20.0
Keyboard = $50.0
Bu yerda:
ArrayList → productlar tartibli ro‘yxati
HashMap → product nomi orqali narx olish
5.24. null bilan ehtiyot bo‘lish
HashMap’da mavjud bo‘lmagan key bo‘yicha get() qilsang, null qaytadi.
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Ali", 90);
System.out.println(scores.get("Sami"));
Natija:
null
Shuning uchun tekshirish yaxshi:
if (scores.containsKey("Sami")) {
System.out.println(scores.get("Sami"));
} else {
System.out.println("Sami topilmadi");
}
Yoki default qiymat berish:
Integer score = scores.getOrDefault("Sami", 0);
System.out.println(score);
Natija:
0
5.25. Beginner xatolar
Xato 1: Array index 1 dan boshlanadi deb o‘ylash
Noto‘g‘ri:
int[] numbers = {10, 20, 30};
System.out.println(numbers[1]); // birinchi element deb o‘ylash
Aslida bu ikkinchi element.
To‘g‘ri:
System.out.println(numbers[0]); // birinchi element
Xato 2: length va size()ni adashtirish
Array:
numbers.length
ArrayList:
names.size()
String:
text.length()
E’tibor ber:
array.length → field
arrayList.size() → method
string.length() → method
Xato 3: ArrayList’da primitive type ishlatish
Noto‘g‘ri:
ArrayList<int> numbers = new ArrayList<>();
To‘g‘ri:
ArrayList<Integer> numbers = new ArrayList<>();
Xato 4: HashMap’da mavjud bo‘lmagan key
Integer score = scores.get("Sami");
System.out.println(score + 10);
Agar "Sami" yo‘q bo‘lsa, score = null. Keyin score + 10 xato berishi mumkin.
Yaxshi variant:
Integer score = scores.getOrDefault("Sami", 0);
System.out.println(score + 10);
5.26. Kichik mashq
Vazifa
Quyidagi ishni bajar:
1. ArrayList ichida 5 ta product nomi saqla
2. HashMap ichida product narxlarini saqla
3. Har bir product nomi va narxini chiqar
4. Narxi 100 dan katta productlarni alohida chiqar
Yechim:
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
ArrayList<String> products = new ArrayList<>();
products.add("Laptop");
products.add("Mouse");
products.add("Keyboard");
products.add("Monitor");
products.add("USB Cable");
HashMap<String, Double> prices = new HashMap<>();
prices.put("Laptop", 1000.0);
prices.put("Mouse", 20.0);
prices.put("Keyboard", 50.0);
prices.put("Monitor", 200.0);
prices.put("USB Cable", 5.0);
System.out.println("All products:");
for (String product : products) {
double price = prices.get(product);
System.out.println(product + " = $" + price);
}
System.out.println("Expensive products:");
for (String product : products) {
double price = prices.get(product);
if (price > 100) {
System.out.println(product + " = $" + price);
}
}
}
}
Natija:
All products:
Laptop = $1000.0
Mouse = $20.0
Keyboard = $50.0
Monitor = $200.0
USB Cable = $5.0
Expensive products:
Laptop = $1000.0
Monitor = $200.0
5.27. Qisqa xulosa
Bu bo‘limda Java’da bir nechta qiymat bilan ishlashni ko‘rdik:
Array → fixed size ro‘yxat
2D array → jadval ko‘rinishidagi array
ArrayList → dynamic size ro‘yxat
HashMap → key-value saqlash
for → index bilan yurish
for-each → elementlar bo‘ylab oson yurish
Eng muhim eslab qoladigan joy:
Array index 0 dan boshlanadi.
Array uzunligi o‘zgarmaydi.
ArrayList uzunligi o‘zgaradi.
HashMap key orqali value topadi.
Keyingi mavzu: Error Handling Basics - Exception, try/catch/finally, checked vs unchecked, throw, throws.