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
233 views
in Technique[技术] by (71.8m points)

Generic type parameter naming convention for Java (with multiple chars)?

In some interfaces I wrote I'd like to name generic type parameters with more than one character to make the code more readable.

Something like....

Map<Key,Value>

Instead of this...

Map<K,V>

But when it comes to methods, the type-parameters look like java-classes which is also confusing.

public void put(Key key, Value value)

This seems like Key and Value are classes. I found or thought of some notations, but nothing like a convention from Sun or a general best-practice.

Alternatives I guessed or found...

Map<KEY,VALUE>
Map<TKey,TValue>
Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

Oracle recommends the following in Java Tutorials > Generics > Generic Types:

Type Parameter Naming Conventions

By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

You'll see these names used throughout the Java SE API and the rest of this lesson.

I'd stick to it to avoid the confusion among the developers and possible maintainers.


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

...