Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

.net - What is difference b/w Generic List and Arraylist, Generic List Vs HashTable, Generic List Vs No Generic?

What is difference between

  1. Generic List and Arraylist
  2. Generic List Vs HashTable
  3. Generic List Vs No Generic?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically, generic collections are type-safe at compile time: you specify which type of object the collection should contain, and the type system will make sure you only put that kind of object in it. Furthermore, you don't need to cast the item when you get it out.

As an example, suppose we wanted a collection of strings. We could use ArrayList like this:

ArrayList list = new ArrayList();
list.Add("hello");
list.Add(new Button()); // Oops! That's not meant to be there...
...
string firstEntry = (string) list[0];

But a List<string> will prevent the invalid entry and avoid the cast:

List<string> list = new List<string>();
list.Add("hello");
list.Add(new Button()); // This won't compile
...
// No need for a cast; guaranteed to be type-safe... although it
// will still throw an exception if the list is empty
string firstEntry = list[0];

Note that generic collections are just one example (albeit the most commonly used one) of the more general feature of generics, which allow you to parameterize a type or method by the type of data it deals with.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...