VOOZH about

URL: https://www.digitalocean.com/community/tutorials/java-generics-example-method-class-interface?comment=176603

⇱ Java Generics Explained: Benefits, Examples, and Best Practices | DigitalOcean


Java Generics Explained: Benefits, Examples, and Best Practices

Updated on June 16, 2026
👁 Java Generics Explained: Benefits, Examples, and Best Practices

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

👁 Vinayak Baranwal
Vinayak Baranwal
Editor
Technical Writer II
See author profile

Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator. Technical Writer @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments.

Category:
Tags:

Still looking for an answer?

Was this helpful?

Hi Thanks for the very informative article… However could you please explain the difference between: public static void printData(List list){ for(Object obj : list){ System.out.print(obj + “::”); } } And public static void printData(List list){ for(Object obj : list){ System.out.print(obj + “::”); } }

- Avinash

hi! i want to devlop my future in java ,i want to learn it i am beginner no from whrere do i start please help me!!!

- Sarah

hi, I want to define my arraylist which allows to insert only class A,B,C .How to achieve in genrics

- sriram

List str=null; str.add(“varun”); str.add(new Integer(10), str); im getting compile time error…plz give me solution .how to add string and integer both in arrylist ???

- varun

i want usecase digram for generics vs collection, its for my job,please give quickly

- RANJITH KUMAR

I want to create xlsx file from a ArrayList. TableBean means a class with some fields and its getter and setter. I have three (3) list 1. ArrayList CompanyBeanList (CompanyBean has 4 fileds with getter - setter) 2.ArrayList EmployeeBeanList (EmployeeBean has 10 fileds with getter - setter) 3.ArrayList ClientBeanList (ClientBeanBean has 8 fileds with getter - setter) I want to call exportToExcel method as exportToExcel(“D:\Back Up\PROJECT\”,CompanyBeanList ,“CompanyBean”) and exportToExcel(“D:\Back Up\PROJECT\”,EmployeeBeanList ,“EmployeeBean”) and exportToExcel(“D:\Back Up\PROJECT\”,ClientBeanList ,“ClientBean”) exportToExcel is a method which create an .xlsx file in the specified path with data from the beanList (2 nd parameter) But problem is i can not pass these 3 different type of list in exportToExcel. Error says The method exportToExcel(String, ArrayList, String) in the type Utility is not applicable for the arguments (String, List, String) (same for other two class) I do not want to write BeanClass name in parameter. it should be parametrized. public static void exportToExcel(String outputPath , ArrayList beanClassName,String sheetName) { try{ Map data = new TreeMap(); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(sheetName); Object[] colName =new Object[20]; if(beanClassName.size()>0) { Field[] field=beanClassName.get(0).getClass().getDeclaredFields(); for(int i=0;i<field.length;i++) { colName[i]=field[i].getName().toUpperCase(); } data.put(“1”, colName); for(int i=0;i<beanClassName.size();i++) { Object[] colValue =new Object[20]; Field[] field1=beanClassName.get(0).getClass().getDeclaredFields(); for(int f=0;i<field1.length;i++) { Method method=null; try { method=beanClassName.get(i).getClass().getMethod(“get”+field1[f].getName().toUpperCase(), null); }catch (IllegalArgumentException e) { log.error("User: “+getUserName()+” : "+“exportToExcel…1…”+e.getMessage()); e.printStackTrace(); } catch (Exception e) { log.error(“User: “+getUserName()+” : “+“exportToExcel…2…”+e.getMessage()); e.printStackTrace(); } colValue[f]=method.invoke(beanClassName.get(i), null); } data.put((i+2)+””, colValue); } Set keyset = data.keySet(); int rownum = 0; for (String key : keyset) { Row row = sheet.createRow(rownum++); Object [] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if(obj instanceof String) cell.setCellValue((String)obj); else if(obj instanceof Integer) cell.setCellValue((Integer)obj); else if(obj instanceof Double) cell.setCellValue((Double)obj); else if(obj instanceof Float) cell.setCellValue((Float)obj); else if(obj instanceof Number) cell.setCellValue((Double)obj); } } try { //Write the workbook in file system FileOutputStream out = new FileOutputStream(new File(outputPath+File.separator+“OrderCounts.xlsx”)); workbook.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); } } else { return; } }catch (Exception e) { log.error("User: “+getUserName()+” : "+“exportToExcel…”+e.getMessage()); e.printStackTrace(); } } I only want to call exportToExcel(“D:\Back Up\PROJECT\”,CompanyBeanList ,“CompanyBean”) and exportToExcel(“D:\Back Up\PROJECT\”,EmployeeBeanList ,“EmployeeBean”) and exportToExcel(“D:\Back Up\PROJECT\”,ClientBeanList ,“ClientBean”) and it will create .xlsx file in the path. That is my main aim. Is it possible.?? Which modification is necessary in exportToExcel method. ??? If solution is known to you please write / modify exportToExcel method as you wish and reply me over mail or post in this site. It is very urgent to me. I am waiting for your reply. I hope i’ll get a suitable solution from you.I believe on you.

- Dev

Thanks for this great article … it was very helpful for me

- Mohsen

Thanks a lot. I made this change in my code and this is working correctly.

- Dev

Hi Respected Sir My expectation is growing high after getting answer from you and solving my previous problem. I face another problem while using java generic in my program. The problem is i have to GROUP BY a ganeric list based on one or two field. Suppose i have a POJO class named StationInformation with CODE,STATION,NAME,ADDRESS i have created a list ArrayList StationInformationList= new ArrayList and populate this list with station data. After some operation with this list object i have to GROUP BY this list based on CODE field and after that CODE and STATION field. This GROUP BY should be same as GROUP BY in database. There is no way to go database from here because data is coming from api. This is very essential to me and i have to resolve it as soon as possible. I hope i’ll get another feedback from you with solution my problem. This GROUP BY is vary urgent and please give me a solution. I am waiting for your answer/reply. Please please sir give me a solution. If possible please give me code example.

- Dev

👁 Creative Commons
This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
  • Deploy on DigitalOcean

    Click below to sign up for DigitalOcean's virtual machines, Databases, and AIML products.

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and AI-native businesses

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.

© 2026 DigitalOcean, LLC.Sitemap.
Dark mode is coming soon.