• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Generic Types  RSS feed

 
Man Ping
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to code a list that has a method, i.e. sum(), that returns the sum of the element(s) in the list if all element(s) in the list are integer or number, and returns the concatenation of string of characters if all element(s) in the list are string (type) using Java to implement the concept of polymorphism in Java? Thanks for helping.
 
Stephan van Hulst
Saloon Keeper
Posts: 7961
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch, Man Ping!

This sounds like a bad idea.

Instead, if you really want to do this, I would suggest making a utility class with several overloaded methods:
Properly functioning lists already exist. Use them.
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ListUtils will unfortunately not compile:

ListUtils.java:10: error: name clash: sum(List<Integer>) and sum(List<String>) have the same erasur
long sum(List<Integer> integers) {
^
ListUtils.java:14: error: name clash: sum(List<Double>) and sum(List<String>) have the same erasure
double sum(List<Double> floats) {
 
Stephan van Hulst
Saloon Keeper
Posts: 7961
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ivan Jozsef Balazs wrote:ListUtils will unfortunately not compile:

ListUtils.java:10: error: name clash: sum(List<Integer>) and sum(List<String>) have the same erasur
long sum(List<Integer> integers) {
^
ListUtils.java:14: error: name clash: sum(List<Double>) and sum(List<String>) have the same erasure
double sum(List<Double> floats) {


That's right, I completely forgot about erasure. The other option is to make a single function that performs an instanceof operation on the first element to determine what type of operation should be performed, and then performing that operation. The main problem is that this method must have Object as its return type.

The only proper solution to the problem is to use separate methods for separate operations:
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!