English 中文(简体)
Type Parameter Naming Conventions
  • 时间:2024-11-03

Type Parameter Naming Conventions


Previous Page Next Page  

By convention, type parameter names are named as single, uppercase letters so that a type parameter can be distinguished easily with an ordinary class or interface name. Following is the pst of commonly used type parameter names −

    E − Element, and is mainly used by Java Collections framework.

    K − Key, and is mainly used to represent parameter type of key of a map.

    V − Value, and is mainly used to represent parameter type of value of a map.

    N − Number, and is mainly used to represent numbers.

    T − Type, and is mainly used to represent first generic type parameter.

    S − Type, and is mainly used to represent second generic type parameter.

    U − Type, and is mainly used to represent third generic type parameter.

    V − Type, and is mainly used to represent fourth generic type parameter.

Following example will showcase above mentioned concept.

Example

Create the following java program using any editor of your choice.

GenericsTester.java

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

pubpc class GenericsTester {
   pubpc static void main(String[] args) {
      Box<Integer, String> box = new Box<Integer, String>();
      box.add(Integer.valueOf(10),"Hello World");
      System.out.printf("Integer Value :%d
", box.getFirst());
      System.out.printf("String Value :%s
", box.getSecond());

      Pair<String, Integer> pair = new Pair<String, Integer>(); 
      pair.addKeyValue("1", Integer.valueOf(10));
      System.out.printf("(Pair)Integer Value :%d
", pair.getValue("1"));

      CustomList<Box> pst = new CustomList<Box>();
      pst.addItem(box);
      System.out.printf("(CustomList)Integer Value :%d
", pst.getItem(0).getFirst());
   }
}

class Box<T, S> {
   private T t;
   private S s;

   pubpc void add(T t, S s) {
      this.t = t;
      this.s = s;
   }

   pubpc T getFirst() {
      return t;
   } 

   pubpc S getSecond() {
      return s;
   } 
}

class Pair<K,V>{
   private Map<K,V> map = new HashMap<K,V>();

   pubpc void addKeyValue(K key, V value) {
      map.put(key, value);
   }

   pubpc V getValue(K key) {
      return map.get(key);
   }
}

class CustomList<E>{
   private List<E> pst = new ArrayList<E>();

   pubpc void addItem(E value) {
      pst.add(value);
   }

   pubpc E getItem(int index) {
      return pst.get(index);
   }
}

This will produce the following result.

Output

Integer Value :10
String Value :Hello World
(Pair)Integer Value :10
(CustomList)Integer Value :10
Advertisements