C # equivalent to support Java get array, install and remove specific index

I am a Java programmer, I used Java ArrayList before, and now I want to have something like this in C #. Some parameters that I need are in this Java code:

 String[] strs = new String[]{"str1" , "str2" , "str3" , "str4"}; ArrayList arrayList = new ArrayList(35); arrayList.add(strs[0]); arrayList.add(strs[1]); arrayList.remove(0); arrayList.set(0, strs[2]); String s = (String) arrayList.get(1); 

I used C # ArrayList and LinkedList , but they do not have these simple parameters that I need. Is there another option in C # that supports accessing objects with indexes, inserting and deleting from a specific index?

+8
java collections arraylist linked-list c #
source share
2 answers

use List <T>

  String[] strs = new String[]{"str1" , "str2" , "str3" , "str4"}; List<string> stringList = new List<string>(); stringList.add(strs[0]); stringList.add(strs[1]); stringList.RemoveAt(indexYouWantToDelete) String s = stringList[0]; 

ArrayLists in C # come from the preceding tho era. Since C # 2.0 has common collections, List <T> is one example of this. As the commentary on this answer says, if you use an ArrayList, the elements you put in the arraylist should be boxed (before Object , because this is the only thing that takes an ArrayList as input). If you want to access them after this, they must be explicitly unpacked, for example, what did you do in your question. (-> String s = (String) arrayList.get(1); )

using shared collections (e.g. List <T> ), there is no longer a box since the compiler knows what data type will consist of a list. In this case, the lines. You can also have List<int> , List<char> or List<whatever> , and you can use the same indexing functions.

+13
source share

Use List<T> ...........................................

which has Add Remove , RemoveAt indexes such as list[i] , etc.

0
source share

All Articles