有什么区别的B / W泛型列表和ArrayList,泛型列表VS哈希表,泛型列表VS不通用? [英] What is difference b/w Generic List and Arraylist, Generic List Vs HashTable, Generic List Vs No Generic?

查看:162
本文介绍了有什么区别的B / W泛型列表和ArrayList,泛型列表VS哈希表,泛型列表VS不通用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是

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

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

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

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

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

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

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

What is difference between

  1. Generic List and Arraylist
  2. Generic List Vs HashTable
  3. 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.

这篇关于有什么区别的B / W泛型列表和ArrayList,泛型列表VS哈希表,泛型列表VS不通用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆