30/09/2018, 21:26
Hàm tìm giá trị max trong mảng arraylist hoặc phần tử cuối cùng trong mảng
trong java có hàm nào mà tìm được giá trị max trong mảng arraylist hoặc phần tử cuỗi cùng trong mảng đấy ạ
Bài liên quan
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
Đây là API đầy đủ của ArrayList trong JDK8 nhé, em xem thử xem
Collections.sort(arrayList); // Sắp xếp
arrayList.get(arrayList.size() - 1); //lấy max
Collections.sort(arrayList); // Sắp xếp
cái này phải viết hàm Comparator nhé,
Integer hay String tự sắp xếp được mà, chỉ kiểu Object mà mình muốn quy định kiểu sắp xếp thì mới phải dùng Comparator thôi bạn
cho e hỏi câu nữa
có vẻ hợp lí nhỉ
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html cái này có đề cập
// ======= DO NOT EDIT MAIN FUNCTION ============
import java.util.;
import java.io.;
import static java.lang.Math.sqrt;
class Main
{
public static int snt(int n) {
if (n < 2) {
public static void f1(ArrayList a){
ArrayList arr=new ArrayList();
int i = 0;
int n = a.size();
for (i = 0; i <n-1; i++) {
if (snt(a.get(i)) == 1 ) {
arr.add(a.get(i));
// break;
}
}
// cái e muốn hỏi
Collections.sort(arr);
arr.get((arr.size() - 1)*(arr.size() - 1));
}
public static void main(String args[]) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
ArrayList a = new ArrayList<>();
System.out.print("Enter number of item: ");
int n = Integer.parseInt(in.readLine());
for(int i = 0; i < n; i++){
System.out.print("Number " + i + " (th): ");
a.add(Integer.parseInt(in.readLine()));
}
f1(a);
System.out.println(“OUTPUT:”);
for(int i = 0; i < n; i++){
System.out.println(a.get(i));
}
}
}
Enter number of item: 5
Number 0 (th): 5
Number 1 (th): 1
Number 2 (th): 3
Number 3 (th): 11
Number 4 (th): 5
Exception in thread “main” java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Main.f1(Main.java:39)
at Main.main(Main.java:53)
C:\Users\Ngoc Lam\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 11 seconds)
e chạy e bị lỗi như này ạ