What does Set<element> mean?

你说的曾经没有我的故事 提交于 2019-12-20 05:48:14

问题


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.

Here's that code:

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

What I can't understand is Set<BluetoothDevice>!

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


回答1:


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

Set<BluetoothDevice> pairedDevices

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.

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 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.

Suggested Reading:

  1. Oracle's tutorial on Generics
  2. Using and Programming Generics in J2SE 5.0
  3. Generics in Java - Wiki
  4. Java theory and practice: Generics gotchas
  5. Java Generics FAQs
  6. Covariance and contravariance


来源:https://stackoverflow.com/questions/17897604/what-does-setelement-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!