有什么区别的B / W泛型列表和ArrayList,泛型列表VS哈希表,泛型列表VS不通用?列表、有什么区别、ArrayList、VS

2023-09-02 02:05:48 作者:偷得浮生

什么是

之间的区别 泛型列表和ArrayList 在泛型列表VS哈希表 在泛型列表VS不通用? 解决方案

基本上,泛型集合是类型安全在编译时:可以指定哪些类型的对象的集合应该包含,并且类型系统将确保你只放那种在它的对象。此外,你不需要投的项目,当你把它弄出来。

作为一个例子,假设我们想要的字符串的集合。我们可以使用的ArrayList 是这样的:

  ArrayList的名单=新的ArrayList();
list.Add(你好);
list.Add(新按钮()); //哎呀!这并不意味着在那里...
...
了firstEntry字符串=(字符串)列表[0];
 

名单,其中,串> 将prevent无效项的和的避免了转换:

 名单,其中,串>名单=新的名单,其中,串>();
list.Add(你好);
list.Add(新按钮()); //这不会编译
...
//不需要强制类型转换;保证是类型安全的...虽然它
//仍然会抛出一个异常,如果该列表是空的
了firstEntry字符串列表= [0];
 

请注意该通用集合只是一个例子(虽然最常用的一种)泛型,它允许你参数由它处理的数据的类型的类型或方法的更一般的功能。

Java泛型

What is difference between

Generic List and Arraylist Generic List Vs HashTable Generic List Vs No Generic?

解决方案

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.