Set<element> 是什么?意思是?

2022-01-18 00:00:00 set tags android java android-arrayadapter

我对 Android 有点陌生,我必须在两个 PCB 之间建立蓝牙连接.我在 API 指南中看到了一行代码,但我仍然没有弄清楚它是什么意思.我想知道是否有人可以帮助我.

I'm kind of new to Android and I have to make a Bluetooth connection between two PCBs. I saw a line of code in API guides and I still haven't figure out what it means. I wonder if someone can help me.

代码如下:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

我看不懂的是Set

他们为什么要在 "< >" 之间添加一些东西.我也见过 ArrayAdapter<String>.这些元素有什么作用?

Why does they put something between "< >". I've also seen than in ArrayAdapter<String>. What these elements do?

推荐答案

这使得 Set 成为 Generic 集.当你声明这个时:

That makes the Set a Generic set. When you declare this :

Set<BluetoothDevice> pairedDevices

意味着 Set 对象应该只包含 BluetoothDevice 类型的对象.通常建议使用泛型集合,因为您可以获得类型安全的直接好处.

means the Set object should contain only objects of type BluetoothDevice. Using generic collections is generally recommended, because you gain the immediate benefit of type safety.

Java 集合框架旨在处理任何类型的对象.在 Java 1.4 和更早的版本中,他们使用 java.lang.Object 作为添加到集合中的任何对象的类型.使用对象时必须将对象显式转换为所需的类型,否则会出现编译时错误.

The Java Collections Framework was designed to handle objects of any type. In Java 1.4 and earlier they used java.lang.Object as the type for any object added to the collection. You had to explicitly cast the objects to the desired type when you used them or else you would get compile-time errors.

Java 泛型,在 Java 5 中引入,提供更强的类型安全性.泛型允许将类型作为参数传递给类、接口和方法声明.例如:

Java Generics, introduced in Java 5, provide stronger type safety. Generics allow types to be passed as parameters to class, interface, and method declarations. For example:

Set<BluetoothDevice> pairedDevices

本例中的 是一个类型参数.使用类型参数,编译器确保我们仅将集合与兼容类型的对象一起使用.另一个好处是我们不需要转换从集合中获得的对象.现在在编译时检测到对象类型错误,而不是在运行时抛出转换异常.

The <BluetoothDevice> in this example is a type parameter. With the type parameter, the compiler ensures that we use the collection with objects of a compatible type only. Another benefit is that we won’t need to cast the objects we get from the collection. Object type errors are now detected at compile time, rather than throwing casting exceptions at runtime.

推荐阅读:

  1. Oracle 的泛型教程
  2. 在 J2SE 5.0 中使用和编程泛型
  3. Java 中的泛型 - 维基
  4. Java 理论与实践:泛型陷阱
  5. Java 泛型常见问题解答
  6. 协变和逆变

相关文章