T
T
thatmaniscool2017-06-13 22:31:08
Java
thatmaniscool, 2017-06-13 22:31:08

SomeInterfacesomeObj construct - how to use it correctly?

First of all I have the following class:

public class Pair <K, V> {
  public K key;
  public V value;
  
  public Pair (K key, V value){
    this.key = key; this.value = value;
  }
}

And interface:
public interface Generator <T> {
  public T next ();
}

I also have a class with the LinkedHashMap extension
import java.util.*;
public class MapData <K, V> extends LinkedHashMap <K, V>{
  
  
  public MapData (Generator <Pair<K, V>> gen, int size){
    for (int i=0; i!=size; i++){
      Pair <K, V> p = gen.next();
      put (p.key, p.value);
    }
  }
  
  
  public static <K, V> MapData <K, V> map (Generator <Pair<K, V>> gen, int size){
    return new MapData (gen, size);
  }
  

  
  public static void main (String [] args){
    System.out.println(MapData.map(new Pair<String, Integer>(), 10), 10); // Не работает...
  }
}

Can't figure out how to pass an argument to the MapData.map() method.
Book Thinking in Java 4th, page 592 - 597

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
one pavel, 2017-06-14
@onepavel

coding without reading books is evil!

package com.company;

import java.util.LinkedHashMap;

public class Main {

    public static void main(String[] args) {
        MapData<String,Integer> mapData = MapData.map(new Zoidberg(), 10);
        System.out.print("");
    }
}

class Pair <K, V> {
    public K key;
    public V value;

    public Pair (K key, V value){
        this.key = key; this.value = value;
    }
}

interface Generator <T> {
    public T next ();
}

class MapData <K, V> extends LinkedHashMap<K, V> {


    public MapData (Generator <Pair<K, V>> gen, int size){
        for (int i=0; i!=size; i++){
            Pair <K, V> p = gen.next();
            put (p.key, p.value);
        }
    }


    public static <K, V> MapData <K, V> map (Generator <Pair<K, V>> gen, int size){
        return new MapData (gen, size);
    }
}

class Zoidberg implements Generator<Pair<String,Integer>> {

    @Override
    public Pair<String, Integer> next() {
        return new Pair<String, Integer>("i_will_read_books", 10);
    }
}

D
Dmitry, 2017-06-13
@dsv

Probably something like this: System.out.println(MapData.map(new Generator(), 10));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question