• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Data Structure Abstraction

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Is there a design pattern or OO concept I can use to abstract a Java data structure in an interface design? I want to be able to accept data structures no matter if they are a List, Stack, or Map, and be able to access values from it in the implementation class.

For example, if I pass in: ['1','2','3','4'] to have it reversed and returned as: ['4','3','2','1'], is there a way to do this no matter the data structure?

Thanks,
Anthony
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, for a simple reason: to be able to do that, you need a data structure in which elements have an order, and the order can be changed - that is, a List.

Reversing the order doesn't make a sense for a Map, because elements in a Map don't have any order. And it doesn't make sense for a Stack, because it would violate the contract of a Stack, namely that it works Last-In-First-Out.

With other words, any data structure for which your reversing algorithm is valid already should implement the List interface.

Of course you could imagine the case that you have a data structure that *could* implement the List interface, but for some reason doesn't. In such a case consider the Adapter pattern.
 
Anthony Ray
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Makes sense, Thanks.
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The only possible way is that your user is willing to get back an ordered data structure, like SortedMap, of course, the original structure is lost.
 
I found some pretty shells, some sea glass and this lovely tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic