mong được giúp đỡ ví dụ về cấu trúc add, remove và find trên array list của java

tmyn091

New Member
18/9/21
2
0
1
ha noi
em đang học về java array list nhưng không hiểu các thức hoạt động và cần ví dụ cụ thể ạ
như hàm add làm sao để thêm tại vị trí X và 0 <= X <= N.
hàm remove phần tử X và 0 <= X <= N-1
hàm find phải viết thế nào để tìm kiếm theo tên phần tử như số thự tự hoặc tên người ạ.
 

Joe

Thành viên VIP
21/1/13
3,011
1,335
113
ArrayList is a special form of an array. While an array is a FINAL object, ArrayList (or List) is NOT. Meaning ArrayList can be expanded or reduced while a FINAL object cannot. Example:
Java:
final int a = 100;  // a is a final integer and cannot be changed
String[] s = new String[10]; // 10 elements are set. NO more, no less. Fixed, FINAL
List<String> lst = new ArrayList<>(); // unlimited elements ranging from 0....infinity
The add, remove, insert or replace work as following:
  • add() appends an element to the end of an ArrayList.
  • remove() is to delete an element at a certain position (index) or by name. The difference is the return of the method
  • insert is to add a new element to the specified position. OLD Element of the position is push down 1 position
  • replace or set() is used to change the element at the given position.
Example:
Java:
// this way
ArrayList<String> al = new ArrayList<>();
// or this way
List<String> list = new ArrayList<>(); // it works because ArrayList implenents the Interface List
//-----------------ADD---------------
al.add("Hello world");
list.add("Hello World");
//-------------Insert----------------
al.add(0, "Chao the gioi"); // position 0 is now "Chao the gioi" and pos. 1 is now "Hello world"
list.add(0, "Chao the gioi");
//----------remove--------------
al.remove(1); // delete element at pos. 1 : here Hello world <<- return Hello world
list.remove("Hello world"); // <<-- return true or false. Similar to list.remove(1);
//---------replace----------------
al.set(0, "Hello world"); // now "Chao the gioi" is replaced by "Hello world"
list.set(0, "Hello world");
FINAL object is different from final primitive that the content of final primitive cannot be changed while only the STRUCTURE of a FINAL object cannot be changed. Example:
Java:
String[] s = { "Hello world", "Chao the gioi" }; // ONLY 2 elements
s[0] = "Allo le monde"; // element 0 is changed. OK
s[2] = "Bon jour"; // boundary exception because s has a structure of 2 elements, NOT 3
To find a certain element (or object) in an ArrayList there are many ways to do that. Up Java 8 you can use Streams which are relatively complex for a newbie like you. The easiest way is a loop with comparison. Example:
Java:
for (int i = 0, mx = al.size(); i < al; ++i)
if ("Hello world".equals(al.get(i)) {
   System.out.println("Found \"Hello world\" at position:"+i);
   break;
}
 
Sửa lần cuối:
  • Like
Reactions: tmyn091

tmyn091

New Member
18/9/21
2
0
1
ha noi
ArrayList is a special form of an array. While an array is a FINAL object, ArrayList (or List) is NOT. Meaning ArrayList can be expanded or reduced while a FINAL object cannot. Example:
Java:
final int a = 100;  // a is a final integer and cannot be changed
String[] s = new String[10]; // 10 elements are set. NO more, no less. Fixed, FINAL
List<String> lst = new ArrayList<>(); // unlimited elements ranging from 0....infinity
The add, remove, insert or replace work as following:
  • add() appends an element to the end of an ArrayList.
  • remove() is to delete an element at a certain position (index) or by name. The difference is the return of the method
  • insert is to add a new element to the specified position. OLD Element of the position is push down 1 position
  • replace or set() is used to change the element at the given position.
Example:
Java:
// this way
ArrayList<String> al = new ArrayList<>();
// or this way
List<String> list = new ArrayList<>(); // it works because ArrayList implenents the Interface List
//-----------------ADD---------------
al.add("Hello world");
list.add("Hello World");
//-------------Insert----------------
al.add(0, "Chao the gioi"); // position 0 is now "Chao the gioi" and pos. 1 is now "Hello world"
list.add(0, "Chao the gioi");
//----------remove--------------
al.remove(1); // delete element at pos. 1 : here Hello world <<- return Hello world
list.remove("Hello world"); // <<-- return true or false. Similar to list.remove(1);
//---------replace----------------
al.set(0, "Hello world"); // now "Chao the gioi" is replaced by "Hello world"
list.set(0, "Hello world");
FINAL object is different from final primitive that the content of final primitive cannot be changed while only the STRUCTURE of a FINAL object cannot be changed. Example:
Java:
String[] s = { "Hello world", "Chao the gioi" }; // ONLY 2 elements
s[0] = "Allo le monde"; // element 0 is changed. OK
s[2] = "Bon jour"; // boundary exception because s has a structure of 2 elements, NOT 3
To find a certain element (or object) in an ArrayList there are many ways to do that. Up Java 8 you can use Streams which are relatively complex for a newbie like you. The easiest way is a loop with comparison. Example:
Java:
for (int i = 0, mx = al.size(); i < al; ++i)
if ("Hello world".equals(al.get(i)) {
   System.out.println("Found \"Hello world\" at position:"+i);
   break;
}
cảm ơn anh/ chị ạ,
cho em hỏi thêm chút nữa ạ,
nếu dùng cấu như này thì thế nào ạ, nếu có thể dùng mong anh cho ví dụ ạ.
Java:
    public void add( int idx, AnyType x )
    {
        if( theItems.length == size( ) )
            ensureCapacity( size( ) * 2 + 1 );

        for( int i = theSize; i > idx; i-- )
            theItems[ i ] = theItems[ i - 1 ];

        theItems[ idx ] = x;
        theSize++; 
    }

và

    public AnyType remove( int idx )
    {
        AnyType removedItem = theItems[ idx ];
       
        for( int i = idx; i < size( ) - 1; i++ )
            theItems[ i ] = theItems[ i + 1 ];
        theSize--;   
       
        return removedItem;
    }
 
Last edited by a moderator:

Joe

Thành viên VIP
21/1/13
3,011
1,335
113
First study this screenshot and post the codes so that they are clearer to read
posting.png

Back to your codes:
WHY you have to do that? Why two superfluous methods add() and remove() when they are already there and do the same tasks what you do?
An ArrayList always makes sure that adding of objects works and increases the capacity when it needs. NO NEED to ensure or to increase the "capacity". Therefore the standard add() and remove() should be used. Only overwrite when the standard methods won't meet your requirements.

WHY NOT SO?
Java:
ArrayList<AnyType> list = new ArrayList<>();

...
public void add(int idx, AnyType at) {
    if (idx < 0) return; // do nothing
    if (idx < list.size()) list.add(idx, at);
    else list.add(at);
}
Bugs in your add(). add() overwrites the existing element at the position i. It can be done with the standard set() method of List or ArrayList (see my previous example), but you do the theSize++; and that falsifies the real size of ArrayList. This bug is dangerous because your ArrayList will contain some NULL elements in some unknown positions.

update:
Your add() and remove() method work with an array and I wonder at the reasons. An extra array won't make any sense to me...
Java:
theItems[ idx ]
 
Sửa lần cuối:
  • Like
Reactions: tmyn091